python paramiko ssh 免密远程登录执行命令

2017-09-18  本文已影响899人  远浅

ssh 秘钥登录

import paramiko
# ssh key
p_key = paramiko.RSAKey.from_private_key_file(
    "c:/Users/37073/.ssh/yourkey", password='xxxxxxxx')
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
# 开始连接服务器
ssh.connect(hostname='xxx.xxx.xxx', port=22, username='root', pkey=p_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command("ls -lh")
# 打印输出
print(stdout.read().decode('GBK', 'ignore'))
# 关闭连接
ssh.close()

假如出现host server not found,请手动登录一次,这是因为known_hosts 没有你的服务器信息

密码登录

import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname='39x.1208x.80x.2x4x1', port=22,username='root', password='password')
stdin, stdout, stderr = ssh.exec_command("ls -lh")
print(stdout.read().decode('GBK', 'ignore'))
ssh.close()

上一篇下一篇

猜你喜欢

热点阅读