简体   繁体   English

Paramiko ssh/sftp 多个命令

[英]Paramiko ssh/ sftp multiple commands

I'm trying to achieve some automation with python and paramiko (with my basic beginner logic).我正在尝试使用 python 和 paramiko(使用我的基本初学者逻辑)实现一些自动化。

The code below I'm happy to say works.下面的代码我很高兴地说有效。 Until I add in the command 'rm -f testtrace.pcap to delete the file once it has been downloaded via sftp.直到我添加命令 'rm -f testtrace.pcap 以删除通过 sftp 下载的文件。

Define login credentials定义登录凭据

host = input("Host: ")
user = input("User: ")
port = 22
password = getpass("Password: ")

Open ssh connection打开 ssh 连接

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=port, username=user, password=password)

Execute command run tcpdump执行命令 run tcpdump

stdin, stdout, stderr = ssh.exec_command('timeout 10 tcpdump port 5060 -nnv -s 0 -w testtrace.pcap')
channel = stdout.channel
channel.recv_exit_status()
ssh.close()

Open sftp connection打开 sftp 连接

transport = paramiko.Transport((host, port))
transport.connect(username=user, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)

File Download文件下载

filepath = '/root/testtrace.pcap'
localpath = 'C:\\Users\\******\\Desktop\\python\\testtrace.pcap'
sftp.get(filepath, localpath)

Execute command delete file执行命令删除文件

stdin, stdout, stderr = ssh.exec_command('rm -f testtrace.pcap')
channel = stdout.channel
channel.recv_exit_status()
ssh.close()

Right so a problem that I've been struggling with for a day or two, I've manage to solve within 10 minute of signing up to Stackoverflow!.没错,我已经苦苦挣扎了一两天的问题,我设法在注册 Stackoverflow 后的 10 分钟内解决了!。

Execute command run tcpdump执行命令 run tcpdump

stdin, stdout, stderr = ssh.exec_command('timeout 10 tcpdump port 5060 -nnv -s 0 -w testtrace.pcap')
channel = stdout.channel
channel.recv_exit_status()

I was closing the ssh connection too early.我过早地关闭了 ssh 连接。 By removing ssh.close() from this section it appears to have solved the issue and now functions correctly.通过从本节中删除 ssh.close() 似乎已经解决了问题并且现在可以正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM