I just created an python script that solve me a problem i need but i want to convert this script to exe file to run it in any windows machine without need of install python on it
I have search of how could i convert the py to exe and run it and i have found that i could use script called py2exe the problem here that i want to convert my file to exe and run it as a windows service continuously on the my PC.
Here is the my script:
import socket, sys, serial
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
# try:
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
# print('Connected with {}:{}'.format(addr[0], addr[1]))
str = conn.recv(100)
n_str = str[8:]
last_c = n_str.find('%')
last_str = n_str[:last_c]
final_str = last_str.replace('+',' ')[:-3]
print(final_str)
try:
pole = serial.Serial('COM4')
pole.write(' \r\n')
pole.write(final_str+'\r\n')
pole.close()
except:
print(Exception.message)
s.close()
Could i have some help here
Python is an interpreted language, not a compiled one. As such, it needs its interpreter in order to be executed.
Bearing that in mind, you can use this: http://www.py2exe.org
More options given here: a good python to exe compiler?
or even better, in here: https://wiki.python.org/moin/DistributionUtilities
Related
I have a code which consists of something similar to this, which works in Linux. Now i want to port this to Windows. I know that Windows uses winsock for socket programming but is it possible to implement this python module "socket" in windows as well?
```
import socket
host = self.config.get_config('BASE_ADDRESS',BASE_ADDRESS_VAL)
port = self.config.get_config('BASE_PORT',BASE_PORT_VAL)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,socket.IPPROTO_UDP)
if sock is None:
print('could not open socket')
sys.exit(1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.append(sock)
self.log.info('Listening to %s:%s' % (host, port))
try:
sock.bind((host, int(port)))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
#sock.bind(("10.0.0.1", ""))
while self.winParent.ongoing==True:
try:
r,w,e = select.select(self.sock, [], self.sock,self.timeout)
for sock in r:
data, addr = sock.recvfrom(556)
#something = sock.recvfrom(556)
#print(something[0].decode())
self.handle(sock, addr, data)
except (Exception, e):
import traceback
self.log.critical('%s\n%s' % (str(e), traceback.format_exc()))
time.sleep(1)
for sock in self.sock:
sock.close()
self.sock = []
My code gets stuck at "r,w,e = select.select(self.sock, [], self.sock,self.timeout)".
On investigating with Wireshark, I can see the following:
[1]: https://i.stack.imgur.com/zNxKH.png
I have the following points of doubt :
(1) Could this be a firewall issue? I have added python.exe to allow through Firewall in Windows Defender. Am I missing something basic?
(2) Should I have the winsock.dll installed separately?
The socket module works just fine on Windows and that's not the source of the problem here. As you've helpfully pointed out, it's select where your code gets stuck (the posix select() is the traditional Unix way of servicing sockets). It's supposed to get stuck, as it's sitting and waiting for incoming packets :) You are sending some packets to it, right?
Since you're expecting incoming UDP packets the Windows Firewall might need additional convincing to allow those. Double-check with a quick Google search.
I have a piece of python code to listen on a port. The end result I want is that when anyone runs nmap against that IP, a custom name shows up in the service name column. To illustrate my requirement, see below screenshot that shows port 666 as the name doom.
I tried searching for solutions without any success.
Below is the python code that I'm using to listen on a port:
import socket
import sys
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
s.close()
If someone could point me in the right direction or help me with the modification I should make to this code, I would really appreciate it.
I've faced an odd problem and I cannot figure out what the reason is! Actually, I've written a simple server in Python which echos whatever the client enters. To test it, I connected to server by telnet, but as soon as I enter a character, it will become echoed! I do not know how to stop it! Actually I want to complete a word and after hitting the enter key, my server echos it.
Here is my simple server:
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 5000 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
while True:
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
conn.close()
s.close()
According to the telnet man page, the client attempts to enter linemode, and will fallback to character mode if the remote server doesn't support it:
Once a connection has been opened, telnet will attempt to enable the TELNET LINEMODE option. If this fails, then telnet will revert to one of two input modes: either “character at a time” or “old line by line” depending on what the remote system supports.
You can change your server-side code to handshake with the client for enabling line-by-line, or you can force the client to use an "old" line-by-line mode, where it buffers the characters locally, and sends them all at once.
To do the former, you should be able to send the following sequence of bytes after the initial connection as found here:
0x255 0x253 0x34
To do the latter, you can do (press ctrl right bracket first), which will enable this mode in the telnet client (assuming you are using the BSD telnet command - on Windows it may be different).
^]toggle localchars
For educational purposes, I set up a server that allows remote command execution on Windows - or rather, I tried to. For some reason, the command line refuses to recognize some of the commands I send, but others work fine. For instance, sending the command echo "Hello World!!!" causes, as it should, a cmd window to pop up reading "Hello World!!!". Fine. But when I send the command shutdown /s /t 30 it gives me the improper syntax / help screen for the shutdown command. When I send the command msg * "Hello World" it tells me that 'msg' is not a recognized internal or external command, operable program, or batch file. Here is my server code:
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 4242)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()
print("Connection established with %s " % str(client_address))
while True:
command = input("Enter a command: ")
connection.send(bytes(command, 'UTF-8'))
confirm = connection.recv(128)
if confirm == "yes":
print("[+] Command executed successfully.")
else:
print("[-] Command failed to execute!!!")
And here is my client code:
import socket
import sys
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 42042)
sock.bind(server_address)
sock.connect(('192.168.1.5', 4242))
while True:
command = str(sock.recv(1024))
try:
os.system(command[2:]) # an odd thing, the commands somehow came out prefaced with "b'". Ideas?
sock.send(bytes("yes", 'UTF-8'))
except:
sock.send(bytes("no", 'UTF-8'))
So yeah, that's that. The fact that only SOME commands are getting screwed up is really confusing me. Anybody have any ideas? Also, what's up with that "b'"?
str(sock.recv(1024)) is not the way to convert a bytes object into a string, you should be using the sock.recv(1024).decode('UTF-8') method
You can look at the documentation for bytes.decode https://docs.python.org/3.4/library/stdtypes.html#bytes.decode
Or this related question Best way to convert string to bytes in Python 3?
Recently, I managed to create sockets on my PC and my Raspberry Pi to enable communication between both devices. Currently, the client is able to automatically send messages to the server. I was wondering, if it is possible to modify the scripts to send tcp data packets instead of purely text messages, as I would very much like to control the raspberry pi using my PC in the future without having the need to ssh/etc.
I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not very sure how to go about doing this. I would appreciate if someone could guide me in the right direction with explanation and some examples if possible.
Anyway here is the server/client script I'm running at the moment:
Client:
import socket
import sys
import struct
import time
#main function
if __name__ == "__main__":
if(len(sys.argv) < 2) :
print 'Usage : python client.py hostname'
sys.exit()
host = sys.argv[1]
port = 8888
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
try:
remote_ip = socket.gethostbyname( host )
s.connect((host, port))
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
message = "Test"
try :
#Set the whole string
while True:
s.send(message)
print 'Message sent successfully'
time.sleep(1)
print 'Sending...'
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
def recv_timeout(the_socket,timeout=2):
#make socket non blocking
the_socket.setblocking(0)
#total data partwise in an array
total_data=[];
data='';
#beginning time
begin=time.time()
while 1:
#if you got some data, then break after timeout
if total_data and time.time()-begin > timeout:
break
#if you got no data at all, wait a little longer, twice the timeout
elif time.time()-begin > timeout*2:
break
#recv something
try:
data = the_socket.recv(8192)
if data:
total_data.append(data)
#change the beginning time for measurement
begin=time.time()
else:
#sleep for sometime to indicate a gap
time.sleep(0.1)
except:
pass
#join all parts to make final string
return ''.join(total_data)
#get reply and print
print recv_timeout(s)
s.close()
Server:
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#Function for handling connections
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Receving Data...\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'Message Received at the server!\n'
print data
if not data:
break
conn.sendall(reply)
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread
start_new_thread(clientthread ,(conn,))
s.close()
socket.socket(socket.AF_INET, socket.SOCK_STREAM) already creates a connection that provides a reliable stream of bytes between two machines. This uses TCP, which is on top of IP and Ethernet. The latter two are package-based, while TCP creates a stream of continuous bytes on top of it. It also adds some error checking and error correction, so it is pretty reliable.
I honestly don't understand what you want to achieve with what you call "send packets". What you don't want to do is to create an implementation of TCP yourself, as that's a non-trivial task, so sending RAW packets is out. In general, even using TCP is already relatively low-level and should be avoided unless really necessary.
Using e.g. ZeroMQ you get a message-based interface that does all the transmission for you. It does so on top of TCP (or other transports) and adds more error correction for e.g. disconnects. There, you also have something like "packets", but those are independent of how many TCP or IP packets were required to send it underneath. If you don't want to implement a specific protocol, I'd suggest you use this framework instead of lowlevel TCP sockets.
Another simple alternative is to use HTTP, for which there is also existing code in Python. The downside is that it is always one side that initiates some communication and the other side only replies. If you want some kind of active notification, you either have to poll or use hacks like delaying an answer.
You are already sending data packets - those packets juts happen to contain text data at the moment. Try looking into pickle in the standard libraries and into pyro.