share-image
ESC

Python3 ssh 远程 Linux

使用 python 3 去连接一台 Linux 主机,需要先安装 paramiko

pip3 install paramiko

连接

import paramiko
def loginMachine(sshHostName, sshUserName, sshPort, sshIdentityFile):
# 加载密钥
sshPrivateKey = paramiko.RSAKey.from_private_key_file(IdentityFile)
# 建立连接
client = paramiko.SSHClient()
# 使用密钥自动登录
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname=sshHostName, username=sshUserName, port=sshPort, pkey=sshPrivateKey)

return client

def executeCommand(sshClient, sshCommand):
# 执行命令
stdin, stdout, stderr = sshClient.exec_command(sshCommand)
directory = str(stdout.read().decode()).split()
print(directory)

if __name__ == '__main__':
HostName = "11.1.1.8"
Port = "22"
UserName = "root"
IdentityFile = "/Users/wenjun/.ssh/xiaoshan"
sshClient = loginMachine(HostName, UserName, Port, IdentityFile)
sshCommand = "cd /opt/ && ls"
executeCommand(sshClient,sshCommand)

文章作者:阿文
文章链接: https://www.awen.me/post/25659.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客
本文于 2018-09-14 发布,已超过半年(2694天),请注意甄别内容是否已过期。