FreezeJ' Blog

paramiko实现ssh跳板机

2020-05-26

#!/usr/bin/python
import paramiko


def jump2server(
        jump_server_ip,
        jump_server_username,
        jump_server_password,
        remote_host_ip,
        remote_host_username,
        remote_host_password,
        remote_ssh_port=22,
        jump_ssh_port=22):
    jump_server = paramiko.SSHClient()
    jump_server.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受key
    jump_server.connect(jump_server_ip, username=jump_server_username, password=jump_server_password)  # 跳板机连接
    jump_transport = jump_server.get_transport()  # 创建Transport对象
    # 建立隧道
    jump_channel = jump_transport.open_channel(kind="direct-tcpip",
                                               dest_addr=(remote_host_ip, remote_ssh_port),
                                               src_addr=(jump_server_ip, jump_ssh_port))
    remote_host = paramiko.SSHClient()
    remote_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 自动接受key

    # 使用密码连接(通过隧道)
    remote_host.connect(remote_host_ip, username=remote_host_username, password=remote_host_password, sock=jump_channel)

    # 使用密钥连接(通过隧道)
    # private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa')
    # remote_host.connect(remote_host_ip,
    # username=remote_host_username,
    # pkey=private_key,
    # sock=jump_channel)
    return remote_host


if __name__ == '__main__':
    server = jump2server(
        jump_server_ip='192.168.56.1',
        jump_server_username='root',
        jump_server_password='xxxxxxxx',
        remote_host_ip='192.168.56.1',
        remote_host_username='root',
        remote_host_password='xxxxxxxx',
    )
    stdin, stdout, stderr = server.exec_command("netstat -ntp | grep ssh")
    print(stdout.read().decode())
    server.close()

输出结果

tcp        0    112 192.168.56.2:22       192.168.56.1:59393    ESTABLISHED 21676/sshd: root@no 
Tags: Python
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏