現(xiàn)在實(shí)驗(yàn)室大部分的服務(wù)器是不允許直接ssh連接的,需要先連到一個(gè)跳轉(zhuǎn)機(jī)逆害,之后再通過(guò)這個(gè)跳轉(zhuǎn)機(jī)去ssh連接服務(wù)器往果。如果是自動(dòng)化連接筑公,如下圖所示:
手工操作的話無(wú)非就是兩次輸入ssh連接命令,如果是腳本自動(dòng)連接的話該怎么做呢孽水,本節(jié)針對(duì)shell腳本與python腳本兩種自動(dòng)化方式實(shí)現(xiàn)ssh遠(yuǎn)程跳轉(zhuǎn)票腰。
shell腳本:
ssh -i id_rsa -F bastion_ssh_config fsp@172.28.55.64
其中id_rsa為ssh連接的私鑰文件(需要提前在目標(biāo)主機(jī)與跳轉(zhuǎn)機(jī)上置入公鑰)。bastion_ssh_config為跳轉(zhuǎn)配置文件女气,內(nèi)容樣例如下:
ControlPersist 15m
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
#172.28.55.64為目標(biāo)主機(jī)的IP杏慰,192.168.35.97為跳轉(zhuǎn)機(jī)的IP
Host 172.28.55.64
ProxyCommand ssh -i id_rsa test@192.168.35.97 -W %h:%p -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null
python腳本:
python ssh_jumphost_connect.py
其中ssh_jumphost_connect.py文件的內(nèi)容樣例如下:
import paramiko
from sshtunnel import SSHTunnelForwarder
#192.168.35.97為跳轉(zhuǎn)機(jī)的IP,172.28.55.64為目標(biāo)主機(jī)的IP炼鞠,
with SSHTunnelForwarder(('192.168.35.97', 22), ssh_username='test', ssh_password='Test@1234', remote_bind_address=('172.28.55.64', 22), local_bind_address=('0.0.0.0', 10022)) as server:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='127.0.0.1', port=10022, username='test', password='Test@1234')
stdin, stdout, stderr = client.exec_command('ls')
print stdout.read()
client.close()
參考鏈接:
https://selivan.github.io/2018/01/29/ansible-ssh-bastion-host.html
https://pypi.org/project/sshtunnel/