python 运程连接 linux

python 实现远程连接,操作linux

1. 安装依赖

pip3 install paramiko

2. 实现原理

# -*- coding: utf-8 -*-
import paramiko


def connect(cmd, try_times=3):
    while True:
        try:
            # 建立一个sshclient对象
            ssh = paramiko.SSHClient()
            # 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 调用connect方法连接服务器
            ssh.connect(hostname='xxx', port=xx, username='xxx', password='xxxx')
            # 执行命令
            stdin, stdout, stderr = ssh.exec_command(cmd)
            # 结果放到stdout中,如果有错误将放到stderr中
            print(stdout.read().decode())
            # 关闭连接
            ssh.close()
            return
        except Exception:
            # 由于异常较多, 这里直接捕获重试
            if try_times != 0:
                try_times -= 1
                print(try_times)
            else:
                exit(1)


if __name__ == '__main__':
    connect("ls -l")

posted @ 2022-12-21 09:43  tt_贝塔  阅读(127)  评论(0编辑  收藏  举报