我使用以下代码打开linux shell,并从python脚本向其发送命令:
#!/usr/bin/env python
import sys,subprocess,pty,os,time,threading
#This script is for Linux
result=""
def SendCommand(master,cmd):#function to send a command to opened shell process
os.write(master, cmd+"\n")
def ReadMasterTo(master):#function to read output of shell and append it to result
global result
while(True):
result+=os.read(master,2048)
def Signal(pid,signalnum):#function to send Signals to a process pid,It is what CTRL+C and ... do.
os.killpg(pid,signalnum)
master, slave = pty.openpty() # I need pty to be able to execute some commands like sudo
SHELL = ["/bin/sh","-i"]#If I use /bin/sh signalling works,but I don't have tty!
#If I use /bin/bash I have tty but signalling doesn't work!
# want both of signalling and tty!
shell = subprocess.Popen(SHELL,preexec_fn=os.setsid,stdin=slave,stdout=slave,stderr=slave,universal_newlines=True)
time.sleep(1)#sleep 1 sec for being sure shell is open
t1 = threading.Thread(target=ReadMasterTo,args=(master,))#Call ReadMasterTo() as a thread to read output of shell and append it to result
t1.daemon=True
t1.start()
print "Started!Waiting..."
print "Ping 127.0.0.1 started."
SendCommand(master,"ping 127.0.0.1")
time.sleep(5)
Signal(shell.pid,2)
print "Ping 127.0.0.1 finished."
print "Ping google.com started."
SendCommand(master,"ping google.com")
time.sleep(5)
Signal(shell.pid,2)
print "Ping operations finished."
SendCommand(master,"echo 1 > ./done")
f=open("result.txt","w")
f.write(result)
f.close()
print "Result was saved to result.txt!\n"
os.system("cat ./result.txt")
print "\nExit"
os._exit
主要问题是: SHELL=[“/bin/sh”,“-i”]#如果我使用/bin/sh信令可以工作,但我没有tty! #如果我使用/bin/bash,我就有tty,但是信令不起作用! #既要信号又要tty!在
如果我使用/bin/bash Signal函数,则不会终止ping进程 如果我使用/bin/sh Signal函数,但我得到以下错误:
^{pr2}$意味着我不能使用基于tty的命令,比如sudo,。。。在
这个python脚本不是从终端运行的,它是从C调用的程序。它将结果保存到一个文件中,C程序处理它。在
在注意:对不起语言错误。我的母语不是英语
目前没有回答
相关问题 更多 >
编程相关推荐