美文网首页
实现机器远程跳转的两种自动化方式

实现机器远程跳转的两种自动化方式

作者: 芳洲拾翠_eff1 | 来源:发表于2018-11-26 16:56 被阅读0次

现在实验室大部分的服务器是不允许直接ssh连接的,需要先连到一个跳转机,之后再通过这个跳转机去ssh连接服务器。如果是自动化连接,如下图所示:



手工操作的话无非就是两次输入ssh连接命令,如果是脚本自动连接的话该怎么做呢,本节针对shell脚本与python脚本两种自动化方式实现ssh远程跳转。

shell脚本:

ssh -i id_rsa -F bastion_ssh_config fsp@172.28.55.64
其中id_rsa为ssh连接的私钥文件(需要提前在目标主机与跳转机上置入公钥)。bastion_ssh_config为跳转配置文件,内容样例如下:

ControlPersist 15m
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
#172.28.55.64为目标主机的IP,192.168.35.97为跳转机的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文件的内容样例如下:

import paramiko
from sshtunnel import SSHTunnelForwarder
#192.168.35.97为跳转机的IP,172.28.55.64为目标主机的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/

相关文章

网友评论

      本文标题:实现机器远程跳转的两种自动化方式

      本文链接:https://www.haomeiwen.com/subject/gvtsqqtx.html