欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python:使用paramiko模块(执行ssh命令,sftp传输文件)

程序员文章站 2022-03-20 14:05:40
...

安装模块

pip3 install paramiko

使用sftp传输文件:

import paramiko

trans = paramiko.Transport(('11.11.12.25', 22))
trans.connect(username='abc', password='123abc')

sftp = paramiko.SFTPClient.from_transport(trans)
sftp.get(remotepath='/home/abc/t.txt',localpath='file')
sftp.put(localpath='file', remotepath='/home/abc/t.txt')
trans.close()

注:

  1. getput方法一次只能传输一个文件,不能传输目录。
  2. localpathremotepath参数都必须具体到文件名,不能是目录,文件名也不能用通配符。
  3. 不管是get还是put,若目标文件存在会直接覆盖。

使用ssh执行命令:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='11.11.12.25', port=22, username='abc', password='123abc')

stdin, stdout, stderr = ssh.exec_command('ls /home/abc')
print("stdout:\n" + stdout.read().decode())
print("stderr:\n" + stderr.read().decode())
print("*"*30)
stdin, stdout, stderr = ssh.exec_command('ls /home/abc')
print("stdout:\n" + stdout.read().decode())
print("stderr:\n" + stderr.read().decode())

ssh.close()
相关标签: 编程语言/Python