Python实现ssh远程执行

2022-09-19 11:38:26 浏览数 (1)

paramiko是基于Python实现的SSH2远程安全连接,支持认证及密钥方式。可以实现远程命令执行、文件传输、中间SSH代理等功能,相对于Pexpect,封装的层次更高,更贴近SSH协议的功能

# ssh执行远程命令脚本

点击查看

代码语言:javascript复制
import paramiko
import sys
def pl_ssh(ip,password,username,cmd,port="22"):
    ssh_client=paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    try:
        ssh_client.connect(hostname=ip,username=username,password=password)
    except Exception as e:
        print('服务器%s连接失败' %ip)
        print(e)
        sys.exit()
    stdin,stdout,stderr=ssh_client.exec_command(cmd)
    print('服务器%s磁盘使用率情况' %ip)
    print(stdout.read().decode("utf-8"))
    ssh_client.close()
if __name__ == '__main__':
    servers={
        "192.168.0.7":{
            "username": "root",
            "password": "hadoop",
            "cmd": "df -h",
            "port": "22"
        },
        "192.168.0.8":{
            "username": "root",
            "password": "hadoop",
            "cmd": "df -h",
            "port": "22"
        }
    }
    for ip,info in servers.items():
        pl_ssh(ip=ip,
               username=info.get("username"),
               password=info.get("password"),
               cmd=info.get("cmd"),
               port=info.get("port")
               )

  • 效果验证

# ssh上传下载文件脚本

点击查看

代码语言:javascript复制
import  paramiko
transport = paramiko.Transport(('192.168.0.66', 22))
transport.connect(username='root', password='hadoop')
sftp = paramiko.SFTPClient.from_transport(transport)  #ftp ssh

#将当前主机F:学习k8s微服务、k8s文档jb51.net.txt文件 放到 192.168.0.66的/home/jb51.net.txt
sftp.put('F:学习k8s微服务、k8s文档jb51.net.txt', '/home/jb51.net.txt')
# 下载用get
# sftp.get('/home/jb51.net.txt', 'F:学习k8s微服务、k8s文档jb51.net.txt')
transport.close()

  • 效果验证
代码语言:javascript复制
[root@summer ~]# cd /home/
[root@summer home]# ll
total 8
-rw-r--r-- 1 root        root        4848 Dec 19 00:30 jb51.net.txt
drwx--x--x 5 summer summer  106 Dec 17 00:36 summer
[root@summer home]# pwd
/home
[root@summer home]# 
ssh

0 人点赞