1、用户名、密码登陆方式
import paramiko
paramiko.util.log_to_file('paramiko.log') # 记录日志文件
ssh = paramiko.SSHClient()
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('139.xx.xx.xx', username='work', password='***')
cmd = 'ls' # 需要执行的Linux命名
stdin, stdout, stderr = ssh.exec_command(cmd) #执行命令后的结构
print(stdout.readlines())
print(stdout.read().decode())
except Exception as e:
print("%s:%s" % (e.__class__, e))
finally:
# 关闭
ssh.close()
2、免密登陆方式
import paramiko
ssh = paramiko.SSHClient()
SSH_PRIVATE_KEY ='/Users/xueerhuan/.ssh/id_rsa' #本地密钥文件路径
try:
key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY) # 无解密密码时
#key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY, password='******') # 有解密密码时,
ssh.load_system_host_keys() #通过known_hosts 方式进行认证可以用这个,如果known_hosts 文件未定义还需要定义 known_hosts
#ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 通过公共方式进行认证 (不需要在known_hosts 文件中存在)
ssh.connect(hostname='139.XX.XX.XX', port=22, username='root', pkey=key)
stdin, stdout, stderr = ssh.exec_command("ps")
# 获取命令结果
result = stdout.read()
# 打印输出
print(result.decode())
except Exception as e:
print("%s:%s" % (e.__class__, e))
finally:
# 关闭
ssh.close()
参考: