python操作ssh


  • 代码如下
import paramiko
import time
from scp import SCPClient
import os

if __name__ == "__main__":
    ip = os.sys.argv[1]
    keyfile = os.sys.argv[2]
    passwd = os.sys.argv[3]
    # 指定本地的RSA私钥文件
    # 如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
    pkey = paramiko.RSAKey.from_private_key_file(
        keyfile, password=passwd)
    print('连接SSH')
    # 建立连接
    trans = paramiko.Transport((ip, 22))
    trans.connect(username='root', pkey=pkey)
    # 将sshclient的对象的transport指定为以上的trans
    ssh = paramiko.SSHClient()
    ssh._transport = trans
    # 执行命令,和传统方法一样
    stdin, stdout, stderr = ssh.exec_command('ls -al')
    print(stdout.read().decode())

    # SCPCLient takes a paramiko transport as an argument
    scp = SCPClient(ssh.get_transport())
    scp.put('test1.txt', '/home/user')
    scp.get('test2.txt')
    # Uploading the 'test' directory with its content in the
    # '/home/user/dump' remote directory
    scp.put('test', recursive=True, remote_path='/home/user/dump')
    scp.close()
    ssh.close()
    # 关闭连接
    trans.close()
    exit(0)

文章作者: Mr.Pan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Mr.Pan !