我有一个程序需要输出三个不断变化的消息。连接数、已用时间和拒绝的连接。
我尝试用以下方式写它们'\r'
在字符串末尾并在其他开始自己的输出循环之前打印换行符,认为回车符会返回一行。但它们最终都在第一行互相覆盖。
我见过类似的问题,人们推荐使用curses
但我似乎无法让它发挥作用。我尝试使用addstr()
代替print
or sys.stdout.write()
但显然我做得不对,因为它最终看起来像this. https://i.stack.imgur.com/08T42.png我也尝试过使用move(0,0)
每次之后addstr
因为我认为坐标可能是根据光标的最后位置计算的,但输出看起来与我没有这样做时相同
这是我当前使用的代码curses
-
from scapy.all import *
from curses import wrapper
import argparse, random, socket, sys, time, os, threading, re, subprocess, curses
def main(target):
try:
stdscr.clear()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
#things regarding user agents and iptables
for conn in range(args.connections):
t = threading.Thread(target=sendPacket, args=(targetIP, args.port, targetHost,random.choice(userAgents)))
threads.append(t)
t.start()
numConn += 1
try:
lock.acquire()
stdscr.addstr(0, 0,'{0} Connections Established to {1} '.format(numConn,getIP(target)))
stdscr.refresh()
#sys.stdout.flush()
finally:
lock.release()
time.sleep(args.timer)
CloseWin()
sys.exit()
except KeyboardInterrupt, e:
lock.acquire()
stdscr.addstr (5,0,'Exiting {0}'.format(e))
CloseWin()
lock.release()
sys.exit()
#functions that deal with resolving host and IP
def sendPacket(targetIP,targetPort,targetHost,userAgent):
try:
#building and sending the packet
failPacket = 0
lock.acquire()
if synack is None:
stdscr.addstr(1, 0, '{0} Connections refused'.format(failPacket))
stdscr.refresh()
failPacket += 1
return
#send final packet
lock.release()
return
except Exception,e:
CloseWin()
#print e
lock.release()
return
def MeasureTime():
try:
lock.acquire()
while True:
stdscr.addstr(3, 0,'{0} Time elapsed'.format(time.time() - startTime))
stdscr.refresh()
finally:
lock.release()
def CloseWin():
try:
lock.acquire()
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
finally:
lock.release()
if __name__ == '__main__':
#args
stdscr = curses.initscr()
if args.debug == True:
wrapper(OneConn(args.target)) #OneConn is the same as the main function except it only opens one connection, so the print is the same
else:
startTime = time.time()
wrapper(main(args.target))
另外,除了写得不正确之外,当我使用时,我似乎无法正确关闭它ctrl+c
试图出去,看起来它停止更新有关数据包的打印输出,但时间仍在继续。除了关闭终端之外我想不出其他方法来阻止它。
尝试根据 @martinaeu 的建议添加锁,并编辑帖子以展示我所做的事情。结果我只能看到time elapsed
在第四行中打印并更新,根本看不到其他打印,并且在不关闭终端的情况下仍然无法退出程序