Python程序远程终端ssh:paramiko的简单应用

编写Python程序,令Windows作为ssh客户端连接到Linux虚拟机

import paramiko

hostname = ''  # 虚拟机的IP地址
username = ''  # 虚拟机的用户名
password = ''  # 虚拟机的密码
#client_hostname,client_username,client_password是Windows的主机名称、用户名称、密码
command = 'sshpass -p client_password scp client_username@client_hostname:D://666.txt /home/cet'  # 要执行的命令
try:
    # 创建SSH客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # 连接到虚拟机
    client.connect(hostname, username=username, password=password)

    # 执行命令
    stdin, stdout, stderr = client.exec_command(command)
    output = stdout.read().decode('utf-8')
    error = stderr.read().decode('utf-8')

    # 输出命令执行结果
    if output:
        print("命令输出:")
        print(output)
    if error:
        print("命令错误:")
        print(error)

    # 关闭SSH连接
    client.close()
except Exception as e:
    print("连接失败:", str(e))