how to transfer a variable from a server to a client. python - python-2.7

So I am really new to server and client code with python and I am doing this project from this book which asks me to do a couple of things. One of them is to transfer all the files so that the client can see them clearly. Here is the code.
Server:
import socket
from PIL import ImageGrab
import sys
sys.path.append(r'C:\Users\Home\Documents\python\new_project')
import pyperclip
import shutil
import glob
import subprocess
host = socket.gethostname()
port = 12346
server_socket = socket.socket()
server_socket.bind((host, port))
Server_online = True
while Server_online:
server_socket.listen(2)
client_socket, client_addr = server_socket.accept()
client_name = client_socket.recv(1024)
if client_name == "Screen Shot":
im = ImageGrab.grab()
f = open('C:\Users\Home\Documents\screen.txt')
i = int(f.read())
f.close()
im.save(r"C:\Users\Home\Documents\python\new_project\screen" + str(i) +'.jpg' )
i = i + 1
f = open('C:\Users\Home\Documents\screen.txt', 'w')
f.write(str(i))
f.close()
client_socket.send("Picture taken")
elif client_name == "Copy":
while 1:
try:
data = client_socket.recv(1024)
Copied = pyperclip.copy(data)
client_socket.send("text copied.")
break
except:
client_socket.send("Failed to copy")
elif client_name == "Paste":
pasting = pyperclip.paste()
elif client_name == "Show files":
while 1:
files = client_socket.recv(1024)
files_list = glob.glob("C\\Users\\Home\\Documents\\" + files + "\\*.*")
client_socket.send(**files_list**)
break
elif client_name == "Exit":
client_socket.sendall("Exting server...")
client_socket.close()
client_socket.close()
server_socket.close()
Client:
import socket
import time
import glob
host = socket.gethostname()
port = 12346
client_socket = socket.socket()
client_socket.connect((host, port))
client_connected = True
while client_connected:
print '''Pick What you want to do.(Screen Shot, Copy, Paste,
Show files, Open files, Copy files, Exit )'''
request = raw_input()
if request == "Screen Shot":
print "Screen shot in 5 seconds"
for i in range(5,0,-1):
print i
time.sleep(1)
client_socket.send("Screen Shot")
print client_socket.recv(1024)
elif request == "Copy":
client_socket.send("Copy")
print "what do u want to be copied:"
Copied = raw_input()
client_socket.send(Copied)
print client_socket.recv(1024)
elif request == "Exit":
client_socket.send("Exit")
print client_socket.recv(1024)
break
elif request == "Paste":
client_socket.send("Paste")
elif request == "Show files":
client_socket.send("Show files")
print "What files do you want to send?"
files = raw_input()
client_socket.send(files)
outcome = client_socket.recv(1024)
try:
for files in outcome:
print files
except:
print "no outcome"
else:
print "Not one of the requests. Enter again."
client_socket.close()
So as you can see it is really easy stuff but what i am stuck on is how to transfer the variable in the "Show files" (server) part where the server sends the client a list of the listed files. (its bloded).
If you can help me out that would be great I have been stuck on this for weeks

Well this is old. I solved this problem later on.
all you need to do is this (better to do it with the struct library):
on the server:
file_list = '\n'.join(file_list)
files_list_len = len(files_list)
client_name.send(files_list_len)
client_name.send(file_list)
client side:
recv_size = client_socket.recv(4)
files = client_socket.recv(recv_size).split("\n")

Related

error "not enough arguments given" when setting a function of a class as a callback

I'm new to python. Following is my code. I get this error when I create an instance of my class.
error from callback >: on_open() takes exactly 2 arguments (1 given)
The same code works alright if I do all of this outside the Class, directly in the main file. I think it has something to do with the 'self' thing(attribute ?). But the similar code on the server side works alright.
I'm using this web-socket-client package! and following the example Long-lived connection shown there.
This is the library! I'm using for the server side, which has pretty similar interface as the client library.
Server Side Code
from websocket_server import WebsocketServer
def client_connected(client, server):
print "connected:"
print client
def client_disconnected(client, server):
print "Disconnected:"
print client
def message_received(client, server, message):
server.send_message(client, message)
print "message received: ", message
print client
server = WebsocketServer(13254, host='127.0.0.1')
server.set_fn_new_client(client_connected)
server.set_fn_client_left(client_disconnected)
server.set_fn_message_received(message_received)
server.run_forever()
Client Side code that works.
import websocket
from multiprocessing import Lock
import copy
import json
import time
import thread
txMsg = "hello world"
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run():
for i in range(1):
time.sleep(1)
print txMsg
ws.send(txMsg)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://127.0.0.1:13254",
on_message = on_message,
on_error = on_error,
on_close = on_close,
on_open = on_open)
ws.run_forever()
Client side code that produces error
import websocket
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Client:
__metaclass__ = Singleton
serverAddress = None
serverPort = None
socket = None
def __init__(self, serverAddress, serverPort):
self.serverAddress= serverAddress
self.serverPort = serverPort
websocket.enableTrace(True)
self.socket = websocket.WebSocketApp("ws://"+ serverAddress +":"+str(serverPort),
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close,
on_open = self.on_open)
# Callbacks------------------------------------------------------------------
def on_open(self, ws):
print "***Connection Opened***"
self.close()
def on_close(self, ws):
print "***Connection Closed***"
def on_message(self, ws, message):
print "Message: ", message
self.socket.close()
def on_error(self, ws, error):
print "Error: ", error
# API------------------------------------------------------------------
def close(self):
self.socket.close()
client = Client('127.0.0.1', 13254)
client.socket.run_forever()
In the source code of the client library, go to "_app.py". In function "_callback" of the class "WebSocketApp" (line 339 at the moment of writing this answer), change
if inspect.ismethod(callback):
to
if not inspect.ismethod(callback):

Get serial number from banner using Python

I am trying to grab the serial number from a Banner. I have successfully done it by storing the banner content in a file, but now I would like to try without storing it in a file. Below is the snippet of code:
import argparse
import logging
import paramiko
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username', password='bad-password-on-purpose')
except:
return client._transport.get_banner()
def GetSerialNo(ip_address,Banner):
fp1=open("Baner","w")
fp1.write(Banner)
fp1.close()
fp2=open("Baner","r")
for line in fp2:
if re.search("System S/N", line):
Serial = line.split()
return Serial[2]
fp2.close()
if __name__ == '__main__':
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='This is a demo script')
parser.add_argument('-s','--ipsetups', help='IP Address')
args = parser.parse_args()
Setup_File=args.ipsetups
fp=open(Setup_File,"r")
for line in fp.readlines():
IP = line.strip()
logger.info("================================ WORKING on %s ===================================",IP)
Banner = grab_banner(IP, 22)
serial = GetSerialNo(IP, Banner)
logger.info("Serial Number is -> %s",serial)
fp.close()
The above code is working fine, but now I am trying to do it by storing it in some variable and then grabbing the serial number. But I'm unable to do so. Below is what I am trying to do:
def get_ip(Setup_File):
IPS = []
with open(Setup_File, 'r') as f:
for line in f:
IPS = line.split()
return IPS
def grab_banner(ip_address, port):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip_address, port=port, username='username', password='bad-password-on-purpose')
except:
return client._transport.get_banner()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='This is a demo script by Mangesh Pardhi.')
parser.add_argument('-s','--ipsetups', help='PD-Setup IP Address')
args = parser.parse_args()
Setup_File=args.ipsetups
print Setup_File
IPS = get_ip(Setup_File)
for IP in IPS:
logger.info("================================ WORKING on %s ===================================",IP)
Banner = grab_banner(IP, 22)
if "System S/N" in Banner:
XXXXXXXXXXHow To procees XXXXXXXXXXx
serial = Serial[2]
logger.info("Serial Number is -> %s",serial)
You could just simplify GetSerialNo in your original code.
def GetSerialNo(ip_address, Banner):
for line in Banner.split('\n'):
if re.search("System S/N", line):
Serial = line.split()
return Serial[2]
(Surely you already know that you don't need the parameter ip_address there.)

Quickfix with several Python strategies

I am having difficulties to trade several trading strategies written in Python.
I have established FIX connection via Quickfix but I only can send orders if the script of the strategy is inside the Quickfix connection script. Since I have several strategies I really have no idea how to send the order from a separate script. Can someone give me some solution?
import sys
import datetime
import time
import quickfix as fix
class Application(fix.Application):
orderID = 0
execID = 0
def gen_ord_id(self):
global orderID
orderID+=1
return orderID
def onCreate(self, sessionID):
return
def onLogon(self, sessionID):
self.sessionID = sessionID
print ("Successful Logon to session '%s'." % sessionID.toString())
return
def onLogout(self, sessionID):
return
def toAdmin(self, message, sessionID):
username = fix.Username("username")
mypass = fix.Password("password")
mycompid = fix.TargetSubID("targetsubid")
message.setField(username)
message.setField(mypass)
message.setField(mycompid)
def fromAdmin(self, message, sessionID):
TradeID = fix.TradingSessionID
message.getField(TradeID)
return
def toApp(self, sessionID, message):
print "Sent the following message: %s" % message.toString()
return
def fromApp(self, message, sessionID):
print "Received the following message: %s" % message.toString()
return
def genOrderID(self):
self.orderID = self.orderID + 1
return `self.orderID`
def genExecID(self):
self.execID = self.execID + 1
return `self.execID`
def put_order(self, sessionID, myinstrument, myquantity):
self.myinstrument = myinstrument
self.myquantity = myquantity
print("Creating the following order: ")
today = datetime.datetime.now()
nextID = today.strftime("%m%d%Y%H%M%S%f")
trade = fix.Message()
trade.getHeader().setField(fix.StringField(8, "FIX.4.4"))
trade.getHeader().setField(fix.MsgType(fix.MsgType_NewOrderSingle))
trade.setField(fix.ClOrdID(nextID)) #11=Unique order
trade.getHeader().setField(fix.Account("account"))
trade.getHeader().setField(fix.TargetSubID("targetsubid"))
trade.setField(fix.Symbol(myinstrument)) #55=SMBL ?
trade.setField(fix.TransactTime())
trade.setField(fix.CharField(54, fix.Side_BUY))
trade.setField(fix.OrdType(fix.OrdType_MARKET)) # 40=2 Limit order
trade.setField(fix.OrderQty(myquantity)) # 38=100
print trade.toString()
fix.Session.sendToTarget(trade, self.sessionID)
try:
file = sys.argv[1]
settings = fix.SessionSettings(file)
application = Application()
storeFactory = fix.FileStoreFactory(settings)
logFactory = fix.ScreenLogFactory(settings)
initiator = fix.SocketInitiator(application, storeFactory, settings, logFactory)
initiator.start()
while 1:
time.sleep(1)
if input == '1':
print "Putin Order"
application.put_order(fix.Application)
if input == '2':
sys.exit(0)
if input == 'd':
import pdb
pdb.set_trace()
else:
print "Valid input is 1 for order, 2 for exit"
except (fix.ConfigError, fix.RuntimeError) as e:
print e
This is my initator app. My question is can I update the following values from another python script:
trade.setField(fix.Symbol(myinstrument))
trade.setField(fix.OrderQty(myquantity))
So I want to change myinstrument and myquantity from another python script and force the initiator to execute the following command application.put_order(fix.Application) with the new values. My question is is this possible at all?
Sounds like you need an internal messaging layer that QuickFIX subscribes to, and that your separate Python scripts publish orders to. It's about workflow design. Try something like VertX as that can be setup using Python.

How do I telnet to a box and read/write username/password from dictionary; and recognize certain prompts

How do I telnet to a box and have it echo what I typed in to verify
I'm truly logged in?????????
telnet = telnetlib.Telnet()
host = "10.59.50.171"
newline = "\n"
telnet = telnetlib.Telnet(host, '23')
telnet.read_until("Username: ".encode())
telnet.write(username)
telnet.read_until("Password: ")
telnet.write(password)
user_acct = {'ADMIN':'PASSWORD','READONLY':'PASSWORD'}
if username in user_acct and password == user_acct[username]:
print('Correct Login')
else:
print('Invalid Login... Please Try Again')
This is an example of how to use the latest pexpect to control a telnet session:
from pexpect import fdpexpect
import pexpect
import select
import socket
class SocketSpawn(fdpexpect.fdspawn):
def read_nonblocking(self, size=1, timeout=-1):
if timeout == -1:
timeout = self.timeout
rlist = [self.child_fd]
wlist = []
xlist = []
rlist, wlist, xlist = select.select(rlist, wlist, xlist, timeout)
if self.child_fd not in rlist:
raise pexpect.exceptions.TIMEOUT('Timeout exceeded.')
return super(fdpexpect.fdspawn, self).read_nonblocking(size)
if __name__ == '__main__':
username = 'username'
password = 'password'
host = '10.59.50.171'
port = 23
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
session = SocketSpawn(s, timeout=10)
session.expect_exact('Username: ')
print session.before
session.write("%s\n" % username)
session.expect_exact('Password: ')
print session.before
session.write("%s\n" % password)
try:
session.expect_exact(pexpect.EOF)
except pexpect.TIMEOUT:
pass
print session.before
You will need the SocketSpawn class to fix a defect that was introduced in the latest versions of pexpect. However, this should also work with older versions of pexpect.

AttributeError: 'NoneType' object has no attribute 'write' and System changes

I know there are tons of posts about the AttributeError: NoneType... but they don't seem to apply. My code has been working for years, and this week i am getting this error. Also, I am not an expert coder.
I checked the Python Path, and it seems normal:
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Python27;C:\Python27\Scripts
When i try to edit the code in Komodo IDE, the autocomplete works fine, e.g., self.ser.write(string) has the write in the suggestion menu.
It is as if it can't find the library. Is that right? How can that be?
I am using XP.
Thanks!
OK, i figured it out. I traced the failure to instantiation of opening a COM port (debugging in Komodo IDE was very helpful). It failed to open the port, and while the wrapper (below) for pyserial caught the error, my code didn't do anything about it. So when i tried to use serial methods, i.e. `ser.write()' (where ser is my port instance) i get the AttributeError.
The port failed to open because of the box on the other end wasn't communicating properly. Resetting this box (a motor controller) fixed the problem.
The wrapper I use for PySerial appears to be in-house code---short but useful. I am sharing it here:
SerialIO: Wrapper for PySerial
#----------------------------------------------------------------------
# serialIO: wrappers for pyserial module for exception handling, etc.
#----------------------------------------------------------------------
# depends on http://pyserial.sourceforge.net/
import serial
import sys
import time
##################################### serial handlers
# all serial commands except stop are filtererd through this
class serialIO():
def __init__(self,port, baudrate, timeout=0.0,echo=False,rtscts=False):
self.port = port
self.br = baudrate
self.to = timeout
self.echo = echo
self.rtscts = rtscts
self.stdout = False
self.ser = None
self.status = "OK"
self.reopen()
def reopen(self):
# first close it if it's already open
if self.ser:
try:
self.ser.close()
except serial.SerialException, v:
self.status = "error"
# do we want stdout (for debug)?
if self.port == "stdout":
self.stdout = True
self.ser = sys.stdout
else: # nope, actually open the prort
try: # xonxoff=True hoses binary polling of Faulhabers!
self.ser = serial.Serial(self.port, self.br,
timeout=self.to,
rtscts =self.rtscts,
xonxoff=False)
except serial.SerialException, v:
self.status = "error"
print str(v)
return(self.status)
def echo(self,str):
pass
# write the given string to the serial device, catching exceptions
def safewrite(self,string,flush=True):
try:
result = self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
except serial.SerialException, v:
print str(v)
return(-1)
return(result)
def REALLYflushInput(self):
""" because ser.flushInput() doesn't seem to work :/"""
if self.stdout:
return
self.ser.flushInput()
time.sleep(0.01)
#self.ser.flushInput()
readstr = ""
incount = self.ser.inWaiting()
while (incount > 0):
readstr += self.ser.read(incount)
time.sleep(0.01)
incount = self.ser.inWaiting()
# write the given string to the serial device
def write(self,string,flush=True):
self.ser.write(string)
if flush:
if self.stdout:
sys.stdout.flush()
else:
self.ser.flushOutput()
def read(self,nb):
return(self.ser.read(nb))
# returns number of bytes successfully read, -1 if error
def saferead(self):
if self.stdout:
return("",0)
nread = 0
try:
incount = self.ser.inWaiting()
except serial.SerialException, v:
incount = 0
raise
rstr = ""
while (incount > 0):
try:
rstr += self.ser.read(incount)
except serial.SerialException, v:
print str(v)
return(rstr,-1)
nread = nread + incount
incount = self.ser.inWaiting()
return(rstr,nread)
def readstr(self):
incount = self.ser.inWaiting()
readstring = ""
while (incount > 0):
readstring += self.ser.read(incount)
incount = self.ser.inWaiting()
if self.echo:
self.log("read %s" % readstring)
return readstring
# resturn a list of available serial devices
def GetPortList(plist):
# for port in portlist:
if len(plist) < 1:
# if no list of portnames, make one
plist = ['COM2','COM3','COM4','COM5']
OKports = []
for port in plist:
ser = None
try:
ser = serial.Serial(port, 9600)
except serial.SerialException, v:
#print str(v)
pass
else:
OKports.append(ser.name)
finally:
if(ser):
ser.close()
return OKports
if __name__ == '__main__':
plist = GetPortList([])
print str(plist)
It looks more as if your variable self.ser has NoneType, so you might need to take a look at the place where you initialize self.ser in your class.
Edit: Looking around it seems that the library you are using is pyserial2.7 right? I have seen at the documentation here a class called just Serial, which also takes as input a port and a baudrate, so I guess it might be the class you need. Maybe you are getting NoneType because that SerialIO is deprecated. I have not been able to find it, but that does not mean it doesn't exist. Objects of class Serial also have a write method according to this documentation.