I have been fighting with a threaded send of an string image over python sockets for a while now and have had no luck on this issue.
code for the client side is:
import socket
from PIL import ImageGrab #windows only screenshot
from threading import Thread
import win32api, win32con
import re
import win32com.client
import getpass
import time
import select
shell = win32com.client.Dispatch("WScript.Shell")
host = raw_input("SERVER:")
dm = win32api.EnumDisplaySettings(None, 0)
dm.PelsHeight = 800
dm.PelsWidth = 600
win32api.ChangeDisplaySettings(dm, 0)
port = 9000
def picture():
while 1:
image = ImageGrab.grab().resize((800,600)) #send screen as string
data = image.tostring()
sendme = (data)
try:
s.sendall(sendme)
print ("sent")
except socket.error as e:
print e
except Exception as e:
print e
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
pict = Thread(target=picture)
pict.start()
while 1:
socket_list = [s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
data = sock.recv(1024)
print data
if "LEFTC" in data:
data = data.replace("LEFTC","")
x = re.findall(r'X(.*?)Y',data)
y = re.findall(r'Y(.*?)EOC',data)
x = str(x)
y = str(y)
#REPLACE CODE TO BE REWRITTEN
x = x.replace("[","").replace("]","").replace("'","").replace(" ","")
y = y.replace("[","").replace("]","").replace("'","").replace(" ","")
print(str(x) + ' X\n')
print(str(y) + ' Y\n')
try:
win32api.SetCursorPos((int(x),int(y))) #click time
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,int(x),int(y),0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,int(x),int(y),0,0)
except Exception as e:
print e
elif "RIGHTC" in data:
data = data.replace("RIGHTC","")
x = re.findall(r'X(.*?)Y',data)
y = re.findall(r'Y(.*?)EOC',data)
x = str(x)
y = str(y)
#REPLACE FUNCTION MAREKD FOR REWRITE
x = x.replace("[","").replace("]","").replace("'","").replace(" ","")
y = y.replace("[","").replace("]","").replace("'","").replace(" ","")
print(str(x) + ' X\n')
print(str(y) + ' Y\n')
try: #click
win32api.SetCursorPos((int(x),int(y)))
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN,int(x),int(y),0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP,int(x),int(y),0,0)
except Exception as e:
print e
else:
#This does not work correctly: only BACKSPACE and the else are working.
if "CAPS" in data:
shell.SendKeys('{CAPSLOCK}')
elif "CAPSOFF" in data:
shell.SendKeys('{CAPSLOCK}')
elif "BACKSPACE" in data:
shell.SendKeys('{BACKSPACE}')
elif "SHIFT" in data:
shell.SendKeys('+' + data)
else:
shell.SendKeys(data)
time.sleep(0.1)
server code is:
import socket
import pygame
from pygame.locals import *
from threading import Thread
x = y = 0
host = ""
#port defined here
port = 9000
#This list is used to make the library more pythonic and compact. This also leads to less source code.
keylist = [pygame.K_a,pygame.K_b,pygame.K_c,pygame.K_d,pygame.K_e,pygame.K_f,pygame.K_g,pygame.K_h,pygame.K_i,pygame.K_j,pygame.K_k,pygame.K_l,pygame.K_m,pygame.K_n,pygame.K_o,pygame.K_p,pygame.K_q,pygame.K_r,pygame.K_s,pygame.K_t,pygame.K_u,pygame.K_v,pygame.K_w,pygame.K_x,pygame.K_y,pygame.K_z]
key = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
i/o function
def ioinput(sock):
while 1:
evt = pygame.event.poll() #has to be in the same while loop as the evt called or wont work.
if evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 1: # one for left
x, y = evt.pos
command = ("LEFTC" + " " + "X" + str(x) + "Y" + str(y) + "EOC")
sock.sendall(command)
elif evt.type == pygame.MOUSEBUTTONDOWN and evt.button == 3: # 3 for right 2 is middle which support comes for later.
x, y = evt.pos
command = ("RIGHTC" + " " + "X" + str(x) + "Y" + str(y) + "EOC")
sock.sendall(command)
elif evt.type == pygame.KEYDOWN:
keyname = pygame.key.name(evt.key)
if evt.key == pygame.K_BACKSPACE:
command = ("BACKSPACE")
sock.sendall(command)
elif evt.key in keylist:
if keyname in key:
command = (keyname)
sock.sendall(command)
def mainloop():
message = []
while 1:
try:
while True:
try:
conn, addr = server.accept()
except socket.error:
break
screen = pygame.display.set_mode((800,600))
clickctrl = Thread(target=ioinput, args=(conn,))
clickctrl.start()
while 1:
d = conn.recv(1024*1024*1)
if not d:
break
else:
message.append(d)
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
except Exception as e:
continue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setblocking(False)
server.bind((host, port))
server.listen(55000)
print "Listening on %s" % ("%s:%s" % server.getsockname())
Main event loop.
mainloop()
The picture thread will run 3 to six times then die however the keyboard and mouse input layer continues to operate. I suspect that the GIL is getting in my way. Am i correct or am I missing something really simple here? This program is supposed to be a simplistic reverse remote desktop appication.
I found the problem after speaking with a good friend. turns out that my server side while loop was setup so that it would break.
i fixed this by changing:
while 1:
d = conn.recv(1024*1024*1)
if not d:
break
else:
message.append(d)
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
to :
while 1:
d = conn.recv(1024*1024*1)
message.append(d)
try:
print("attempting to parse..")
data = ''.join(message)
image = pygame.image.frombuffer(data,(800,600),"RGB")
screen.blit(image,(0,0))
pygame.display.flip()
print("recieved pic")
except Exception as e:
print e
continue
Also, client side on the picture thread i added a time.sleep (1) after the exception handling, otherwise the image does not come though correctly.
Related
I currently host the English Amiga Board (EAB) FTP, a FTP server filled with the classic Amiga computer goodies. It is open to everyone but users can also register their own account. I got help in creating a python script that checks that the username being registered at the FTP is a valid account on the EAB forums and that it has at least 50 posts.
However, I've now updated the server (fedora server) and the Python version was updated to 3.7.6. The script have now stopped working and I'm unable to reach the original author.
# python ./eab_post_count.py -u Turran
Traceback (most recent call last):
File "./eab_post_count.py", line 3, in <module>
import sys, re, urllib2
ModuleNotFoundError: No module named 'urllib2'
This script should return "0" if the user exists and have 50 posts.
While I script in some languages, python is not one of them so I would be grateful for any help to modify it to not use urllib2, which I understand is no longer valid for Python 3.
The script:
#!/usr/bin/env python
import sys, re, urllib2
titlecmd = "eab_post_count.py"
version = "1.15"
ignorecase = 0
lastpost = 0
userfound = False
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
def parseurl(url):
if not url:
print("Empty URL!")
sys.exit(3)
headers = { 'User-Agent' : 'Mozilla/5.0' }
request = urllib2.Request(url, None, headers)
try:
response = urllib2.urlopen(request)
except Exception:
print('URL open failed, EAB down?')
sys.exit(2)
content = response.read()
return content
def pagesearch(content, trigger, start, end):
sane = 0
needlestack = []
while sane == 0:
curpos = content.find(trigger)
if curpos >= 0:
testlen = len(content)
content = content[curpos:testlen]
curpos = content.find('"')
testlen = len(content)
content = content[curpos+1:testlen]
curpos = content.find(end)
needle = content[0:curpos]
result = content[len(start):curpos]
if needle.startswith(start):
needlestack.append(result)
else:
sane = 1
return needlestack
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
# this has to be last:
s = s.replace("&", "&")
return s
for idx, arg in enumerate(sys.argv):
if arg == '-h':
print(titlecmd + ' v' + version +' by modrobert in 2017')
print('Function: Returns the number of posts for a given EAB forum user.')
print('Syntax : ' + titlecmd + ' -u <username> [-i] [-l YYYY-MM-DD]')
print('Options : -h this help text.')
print(' : -i ignore case sensivity in user name.')
print(' -l last post after YYYY-MM-DD required.')
print(' -u followed by user name.')
print('Result : 0 = user found, 1 = user not found, 2 = EAB down, 3 = other fail.')
sys.exit(3)
if arg == '-u':
try:
username = sys.argv[idx+1]
except IndexError:
print('Missing username.')
sys.exit(3)
usernameurl = re.sub('[ ]', '%20', username)
if arg == '-i':
ignorecase = 1
if arg == '-l':
lastpost = 1
try:
lpdate = sys.argv[idx+1]
except IndexError:
print('Missing date.')
sys.exit(3)
try:
username
except NameError:
print('Username -u option required.')
sys.exit(3)
if lastpost:
eaburl = "http://eab.abime.net/memberlist.php?do=getall&pp=100&lastpostafter=" + lpdate + "&ausername=" + usernameurl
else:
eaburl = "http://eab.abime.net/memberlist.php?do=getall&pp=100&ausername=" + usernameurl
eabcontent = parseurl(eaburl)
countlist = pagesearch(eabcontent, 'td class', 'alt2">', '</td>')
userlist = pagesearch(eabcontent, 'member.php?', '>', '</a>')
for idx, item in enumerate(userlist):
# lets strip those fancy moderators and admins
userstr = re.sub('<[^<]+?>', '', item)
if ignorecase:
if unescape(str.lower(userstr)) == str.lower(username):
userfound = True;
break
else:
if unescape(str(userstr)) == username:
userfound = True;
break
if userfound == False:
print("User not found: " + username)
sys.exit(1)
usercount = idx
for idx, item in enumerate(countlist):
# hairy stuff below ;)
if idx < (3 * usercount):
continue
stripitem = re.sub('[,]', '', item)
try:
print(int(stripitem))
sys.exit(0)
except Exception:
continue
Thanks in advance!
I am using below provided code to retrive some data with the socket. Issue with this code, it prints all the results till it breaks eventhough I only care for the received line right before it breaks, the second last in other words. So, I need some help to understand how that can be achieved.
import socket
import time
socket.setdefaulttimeout(10)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("192.168.50.102", 2102))
curIndex = "0"
while True:
sending_data = 'get,trx,'+curIndex
#print sending_data
client.send(sending_data)
data = client.recv(128)
print data.encode('UTF-8')
if data == "trx,notfound": break
spdata = data.split(",")
#print spdata[2] + 'kg' #Prints weight + kg
if len(spdata) >= 3:
curIndex = spdata[1]
time.sleep(0.5)
client.close()
Actual output
trx,2,1.250,0.000,19-07-11 14:08:01
trx,3,0.500,0.000,19-07-11 14:19:24
trx,4,0.500,0.000,19-07-11 15:04:37
trx,5,0.250,0.000,19-07-11 15:05:31
trx,6,0.177,0.000,19-07-11 21:06:59
trx,7,0.108,0.000,19-07-12 14:54:00
trx,8,0.106,0.000,19-07-16 17:51:06
trx,9,0.106,0.000,19-07-16 17:54:24
trx,10,0.106,0.000,19-07-18 14:31:49
trx,11,0.171,0.000,19-07-18 14:51:31
trx,notfound
Desired output
trx,11,0.171,0.000,19-07-18 14:51:31
Do not print it : save it.
Replace :
print data.encode('UTF-8')
if data == "trx,notfound": break
By
if data == "trx,notfound": break
last_data = data.encode('UTF-8')
Then, at the end (like after client.close()) you can print last_data
try
data_b = client.recv(1024)
while data_b:
data_b = client_socket.recv(1024)
data += data_b
instead of
data = client.recv(128)
example
import socket
def main():
port = 'Your port'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", int(port)))
server_socket.listen(5)
print('TCPServer Waiting for client on port '+port+'\n')
while True:
print('Listening ...', end='\r')
client, address = server_socket.accept()
print("Connection from ", address[0])
data = None
while True:
data_b = client.recv(1024)
data = data_b
if data_b:
print("Receiving a file...")
while data_b:
data_b = client_socket.recv(1024)
data += data_b
else:
break
print(data.decode())
client.close()
if __name__ == '__main__':
main()
this code I use below is a ZMQ sub to a publisher that is giving me data. It uses the counter to tell me when its 30 and 59 seconds to run my write to CSV every 30 seconds or so.
Problem: I am now timing all of the processes in my thread. the lines where message and message2 = socket.recv_string() is taking anywhere from half a second to 20 seconds to receive string. Thus causing the thread to miss the 30 and 59 second intervals I set. This was not happening yesterday. The other timers for the if statements are taking .00001 or 0.0 seconds. So that part isnt the problem
Im wondering what could effect this. Could it be the processing power of my computer? Or is the receive string based on how long it waits for the publisher to actually send something?
I'm not running in a dev or production environment and its on a shared server with something like 15 other people and its virtual. A zero client. I've never had this problem before and on another script i have set up for another ZMQ pub/sub I'm receiving messages in .01 or .001 seconds all the way to 3 seconds. Which is more manageable but the norm was .01.
Any tips or help would be amazing. Thanks in advance
import zmq
import pandas as pd
import time
import threading
df_fills = pd.DataFrame()
df_signal = pd.DataFrame()
second_v = [30,59]
s = 0
m = 0
h = 0
d = 0
def counter():
global h,s,m,d
while True:
s += 1
#print("Second:{}".format(s))
if s >=60:
m +=1
s = 0
if m >= 60:
h += 1
m = 0
if h >= 24:
d += 1
h = 0
#print(s)
time.sleep(1)
class zmq_thread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global df_fills, second_v,s
print('zmq started')
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect(SERVER)
socket.setsockopt_string(zmq.SUBSCRIBE,'F')
print('socket connected')
tickers = [a bunch of tickers]
while True:
try:
start2 = time.time()
if s == 30:
print('break')
if df_fills.empty == True:
print('running fill thread again')
z = zmq_thread('Start_ZMQ')
#time.sleep(.7)
z.run()
else:
start = time.time()
print('writing fills')
filename = "a CSV"
with open(filename, 'a') as f:
df_fills.to_csv(f, encoding = 'utf-8', index = False, header = False)
f.close()
print('wrote fills')
end = time.time()
print(end-start)
df_fills = df_fills.iloc[0:0]
z = zmq_thread('Start_ZMQ')
z.run()
return df_fills
end2 = time.time()
print(end2-start2)
start3 = time.time()
message = socket.recv_string()
message2 = socket.recv_string()
end3 = time.time()
print(end3-start3, 'message timing')
print(s)
start1 = time.time()
if message == 'F':
# message2_split = message2.split("'")
message2_split = message2.split(";")
message3_split = [e[3:] for e in message2_split]
message4 = pd.Series(message3_split)
if message4[0] in tickers:
df_fills = df_fills.append(message4, ignore_index=True)
print('fill')
end1 = time.time()
print(end1-start1)
except KeyboardInterrupt:
break
counter = threading.Thread(target = counter)
zmq_loop = zmq_thread('Start_ZMQ')
#%%
counter.start()
zmq_loop.start()
I didn't realize that ZMQ typical recv_string is by default blocking. So I did this
message = socket.recv_string(flags = zmq.NOBLOCK)
message2 = socket.recv_string(flags = zmq.NOBLOCK)
except zmq.ZMQError as e:
if e.errno == zmq.EAGAIN:
pass
else:
if message == 'ABA_BB':
message2_split = message2.split(";")
message3_split = [e[3:] for e in message2_split]
message4 = pd.Series(message3_split)
#print(message4)
if message4[2] == '300':
df_signal = df_signal.append(message4, ignore_index=True)
print('Signal Appended')
A while ago I wrote a server in python 3.6 on a windows 7 machine, and it worked there. I have since transfered the server to linux mint 18.3 Sylvia with Cinnamon desktop. For some reason, the program is not accepting connections, even after changing the port from 80 to 8080. I determined this from using internet explorer on another machine to diagnose network issues (yes I did put :8080 after the ip address). My question is: what exactly should I do in order to make the program usable on the linux machine?
Here is the code:
import socket
import sys
import os
from _thread import *
def filterHTML(data):
count = 0
word = ""
loc = data.find("HTTP")
req = ""
while True:
if (data[count] == ' '):
count+=1
break
else:
req+=data[count]
count+=1
while True:
if (count == loc - 1):
break
elif (data[count] == '?'):
break
else:
word+=data[count]
count+=1
return req, word
def getEnd(data):
lng = len(data)
location = 0
for i in range(0,lng,1):
if (data[i] == '/'):
location = i
newstring = ""
for e in range(location, lng, 1):
newstring+=data[e]
return newstring
def threaded_client(Connection):
while True:
print("recieving data from client")
try:
data = Connection.recv(4096)
data = data.decode('utf-8')
print(data)
com, param = filterHTML(data)
if (com == "GET"):
end = getEnd(param)
print(param)
if (param == "/"):
sendFileContent(Connection,"text","init.html")
elif (end == "/favicon.ico"):
sendFileContent(Connection,"bin","favicon.bmp")
elif (param == "/main/" or param == "/main"):
sendFileContent(Connection,"text","main.html")
elif (end == "/BSS.png"):
sendFileContent(Connection,"bin","BSS.png")
elif (param == "/Contact/"):
sendFileContent(Connection,"text","contact.html")
elif (param == "/Projects/"):
sendFileContent(Connection,"text","projects.html")
elif (end == "/cypher.png"):
sendFileContent(Connection,"bin","cypher.png")
elif (end == "/stockOrder.png"):
sendFileContent(Connection,"bin","stockOrder.png")
elif (end == "/website.png"):
sendFileContent(Connection,"bin","website.png")
elif (end == "/background.png"):
sendFileContent(Connection,"bin","background.png")
else:
sendFileContent(Connection,"text","404.html")
Connection.close()
return
except error:
print("client " + str(Connection) + "timed out")
Connection.close()
def sendFileContent(connection,ftype,fileName):
if (ftype == "text"):
try:
FileToSend = open(fileName, "r")
FileContent = FileToSend.read()
connection.sendall(str.encode((FileContent)))
FileToSend.close()
return
except Exception as e:
print("an error occured\n" + str(e))
return
elif (ftype == "bin"):
try:
FileToSend = open(fileName, "rb")
FileContent= FileToSend.read()
connection.sendall((FileContent))
FileToSend.close()
except Exception as e:
print("an error occured\n" + str(e))
return
else:
print("a thingir happened, don't know what")
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print("socket created successfully")
try:
connection.bind((host, 8080))
print("bind complete")
except socket.error:
print(str(socket.error))
connection.listen(128)
count = 0
while True:
clientConnection, address = connection.accept()
clientConnection.settimeout(60.0*5.0)
print("connected to: " + address[0] + " : " + str(address[1]))
count+=1
print(str(count) + " clients so far")
start_new_thread(threaded_client, (clientConnection,))
I don't have enough points to comment, so:
Make sure that your ports are open on your Linux device. First check if you have a firewall up and running by sudo ufw status. If it's up allow the ports you want to access by sudo ufw allow 8080 or sudo ufw allow 80.
As soon as your ports are open and accessible, there's no reason for it not to run.
I hope this helps.
experts
I meet an value missing error in my code , but I think the variable in function are claimed. I don't know why it is happens.
$ python check_rsg_V0312.py
2018-03-20 13:05:49 === Script Start ===
2018-03-20 13:05:49 Monitoring via remote logon
The authenticity of host 'rpahost0 ([127.0.0.1]:7000)' can't be established.
RSA key fingerprint is 2d:f5:67:75:84:b6:24:45:e6:48:60:65:61:ca:69:f7.
Are you sure you want to continue connecting
(yes/no)? yes
Warning: Permanently added 'rpahost0' (RSA) to the list of known hosts.
Password:
Traceback (most recent call last):
File "check_rsg_V0312.py", line 89, in <module>
label = ssh_cmd(nLocalport, rsg_target, ouser, lookip, opasw, command,)
File "check_rsg_V0312.py", line 79, in ssh_cmd
print (ssh.before.decode(),ssh.after().decode())
TypeError: __init__() missing 1 required positional argument: 'value'
Below is my code, it is really strange that one error happens in ssh_cmd
function. detailed please review comments in code.
import os,time,pexpect,re, subprocess, smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
#-----------------------------------------
dir = os.environ['HOME']
ouser = 'x02d726'
opasw = 'qwe12'
nLocalport = 7000
lookip = '127.0.0.1'
rsg_target = "rpahost0"
command = "ls -ltrh | grep tunnel | tail"
nstage = 0
mail_addr = 'cheng.huang#qq.com'
otp_file = dir + '/otplist/C591260'
otp_list = []
rsg_file = dir + '/.rsg_hosts'
known_hosts = dir + '/.ssh/known_hosts'
rsg_port = "auto"
#-----------------------------------------
def printlog(prompt):
year, mon, mday, hour, min, sec, wday, yday, isdst = time.localtime()
print("%04d-%02d-%02d %02d:%02d:%02d %s" % (year, mon , mday, hour, min,
sec, prompt))
def get_egw_name(ref_arr, key):
for oneline in ref_arr:
if (re.search(key, oneline)):
templine = oneline
oneline = re.sub('^\s+|\s+$','',oneline)
egw_ssg = re.split('\s+',oneline)[2]
result = re.split(':',egw_ssg)[0]
return result
def sendworker(to_addr):
from_addr = 'itk-bj.ericsson.se'
smtp_server = 'smtp.eamcs.ericsson.se'
msg = MIMEText('There is no otp left ,please input new OTP list',
'plain', 'utf-8')
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = Header(u'OTP List is Blank', 'utf-8')
server = smtplib.SMTP(smtp_server, 25)
#server.set_debuglevel(1)
server.sendmail(from_addr, to_addr, msg.as_string())
server.quit()
def ssh_cmd(port, target, user, ip, pasw, cmd ):
printlog("=== Script Start ===")
printlog("Monitoring via remote logon")
time.sleep(1)
ssh = pexpect.spawn('/usr/bin/ssh -p %s -o HostKeyAlias=%s %s#%s %s' %
(port, target, user, ip, cmd ),timeout=6000)
try:
i = ssh.expect(['Password: ', 'continue connecting (yes/no)?'],
timeout=15)
if i == 0 :
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline(pasw)
elif i == 1:
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline('yes')
ssh.expect('Password: ')
print(ssh.before.decode(),ssh.after.decode())
ssh.sendline(pasw)
except pexpect.EOF:
print ("no connection EOF,please check RSG tunnel")
except pexpect.TIMEOUT:
print ("your pexpect has TIMEOUT")
else:
ssh.expect(pexpect.EOF)
print (ssh.before.decode(),ssh.after().decode()) # if I disable this line, there will be no error.
flag = ssh.before.decode()
return flag
ssh.close()
if __name__ == '__main__':
if os.path.exists(os.environ['HOME'] + "/.ssh/known_hosts"):
os.remove(known_hosts)
else:
pass
label = ssh_cmd(nLocalport, rsg_target, ouser, lookip, opasw, command)
if re.search('tunnel_check', str(label)):
nstage = 1
if (nstage == 0):
printlog("Tunnel was down and will re-establish now\n")
rsg = open (rsg_file,'r')
rsg_in = rsg.readlines()
rsg.close()
egwname = get_egw_name(rsg_in, rsg_target)
try :
otp = open(otp_file, 'r')
otp_arrary = otp.readlines()
otp.close()
for ot in otp_arrary:
ot = ot.strip()
ot = ot.replace('^\s*|\s*$', '')
otp_list.append(ot)
otp_num = len(otp_list) + 1
if (otp_num > 0):
os.remove(rsg_file)
try :
new_otp = otp_list[0]
except IndexError:
printlog('There is no otp left ,please input new OTP list')
sendworker(mail_addr)
sys.exit()
else:
out = open(rsg_file, 'w')
for line in rsg_in :
line = line.strip()
line = line.replace('^\s+|\s+$','')
if (re.match(egwname, line)):
temp_line = line
old_otp = re.split('\s+',temp_line)[5]
old_otp = old_otp.replace('^\s+|\s+$', '')
line = line.replace(old_otp, new_otp).replace('\\','')
printlog(line + "\n")
out.write(line + "\n")
out.close()
os.remove(otp_file)
time.sleep(1)
outotp = open(otp_file , 'w+')
i = 0
while (i < len(otp_list)):
outotp.write(otp_list[i] + "\n")
i += 1
outotp.close()
os.system("pkill -9 -f \"ssh\.\*-L " + str(nLocalport) + "\"")
os.system("sleep 10")
os.system("pkill -9 -f \"rtunnel\.\*-p " + str(nLocalport) + "\"")
os.system("nohup /opt/ericsson/itk/bin/rtunnel -d -q -g -p " + str(nLocalport) + "-rp auto " + rsg_target + " &")
os.system("sleep 10")
printlog("Kill the rtunnel process\n");
printlog("Tunnel is re-established again\n");
else:
sendworker(mail_addr)
except IOError:
print ("File is not accessible.")
else:
printlog("Tunnel OK")
As you see , after disable the line in Try... else... block, the code will be OK.
else:
ssh.expect(pexpect.EOF)
print (ssh.before.decode(),ssh.after().decode()) # if I disable this line, there will be no error.
flag = ssh.before.decode()
return flag
If you look carefully your traceback, you will find the problem:
Instead of:
print (ssh.before.decode(),ssh.after().decode())
you should write
print (ssh.before.decode(),ssh.after.decode())
after is a method which return string, not a function.
BTW, I think you should put decoding/encoding in your pexpect constructor.