使用 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)
|
评论
0 条评论