python ssh连接远程操作
# coding=utf-8
import paramiko
# 创建ssh对象
ssh = paramiko.SSHClient()
# 把要连接的机器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname="192.168.209.128", port=22, username="root", password="123456")
# 执行命令,多个命令用;分割
stdin, stdout, stderr = ssh.exec_command("ls -l")
res = stdout.read()
if not res:
res = stdout.read()
ssh.close()
print(res.decode())
# 简单方法封装
# 执行远程ssh命令
def exe_ssh_command(cmd, hostname, port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, port, username, password)
stdin, stdout, stderr = ssh.exec_command(cmd)
res = stdout.read()
if not res:
res = stdout.read()
ssh.close()
print(res.decode())