使用 python 3 去连接一台 Linux 主机,需要先安装 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)
|
文章作者:阿文
版权声明:本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0 许可协议。转载请注明来自
阿文的博客!