python结束远端计算机的进程_Paramiko和exec_命令-终止远程进程?

虽然不是最有效的方法,但这应该是可行的。在键盘中断处理程序中,您可以exec_command("killall -u %s tail" % uname)这样:#!/usr/bin/env python2

import paramiko

import select

import time

ltime = time.time()

# Or use random:

# import random

# ltime = random.randint(0, 500)

uname = "victorhooi"

client = paramiko.SSHClient()

client.load_system_host_keys()

client.connect('someserver', username=uname, password='blahblah')

transport = client.get_transport()

channel = transport.open_session()

channel.exec_command("tail -%df /home/victorhooi/macbeth.txt" % ltime)

while True:

try:

rl, wl, xl = select.select([channel],[],[],0.0)

if len(rl) > 0:

# Must be stdout

print channel.recv(1024)

except KeyboardInterrupt:

print("Caught control-C")

channel.close()

try:

# open new socket and kill the proc..

client.get_transport().open_session().exec_command("kill -9 `ps -fu %s | grep 'tail -%df /home/victorhooi/macbeth.txt' | grep -v grep | awk '{print $2}'`" % (uname, ltime))

except:

pass

client.close()

exit(0)

这将杀死任何名为tail的打开进程。但如果您打开了不想关闭的tail,那么这可能会导致问题,如果是这样,您可以grepaps,获取pid和kill -9。

首先,将tail设置为在执行以下操作之前从文件末尾读取n行。将n设置为像time.time()这样的唯一数字,因为tail不关心该数字是否大于文件中的行数,所以time.time()中的大数字不应该引起问题,并且将是唯一的。然后grep为ps中的唯一数字:client.get_transport().open_session().exec_command("kill -9 `ps -fu %s | grep 'tail -%df /home/victorhooi/macbeth.txt' | grep -v grep | awk '{print $2}'`" % (uname, ltime))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值