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)