I am trying to figure out if I can manage my installed program through checking if its running or not. So right now I currently using this script as my basis to monitor my local application.
import os
import sys
import subprocess
import time
while True:
time.sleep(1)
if 'Python_Script.exe' not in subprocess.Popen('tasklist', stdout=subprocess.PIPE).communicate()[0]:
print 'Application was closed'
Note: this is my local application and my aim is to check the status for each clients e.g. (192.168.21.2, 192.168.21.3, 192.168.21.4, 192.168.21.5),
First, you should write a program that can send the output to your computer.
I recommend socket. Here is a simple program that can send some text to the server:
from socket import *
def server():
try:
s = socket(AF_INET, SOCK_DGRAM)
port = int(input('Enter the port: '))
s.bind(('', port))
while True:
print('\nWaiting for a massage...')
msg = s.recvfrom(1024)
print(msg)
except KeyboardInterrupt:
f.close
print('\n\nServer exit.')
def client():
s = socket(AF_INET, SOCK_DGRAM)
host = str(input('\nEnter the server\'s IP: '))
port = int(input('Enter the port: '))
s.sendto("Here is the text that you'd like send to the server")\
.encode('UTF-8'), (host, port))
print('\nThe massage has been send.')
This is a Python 3 program. Maybe you should convert it to Python 2.
You can write your program as a function, and return 'Application was closed' then send it.
However this is just an example, you need write the full program yourself. Good luck :)
Related
I have 2 python scripts.
To make it simple
1st script :
It is a simple infinite while loop in which a variable 'x' is being increased by 1(This script is always running)
Now what I want a 2nd script, when I call this script it should give me the present value of x
I read about multiprocessing ,pipe and queue but was not able to implement it
EDIT:
I tried the socket solution and I am getting errors
Client Side
import serial
import time
from multiprocessing import Process
import sys
import socket
s=socket.socket()
port=43470
s.connect(('127.0.0.1',port))
sertx = serial.Serial('COM4', 115200)
while 1:
for i in range(4):
msg = str(i+1)
# print('sending: ',msg.encode())
msgstat = 'A' + msg
#print(msgstat)
#print(type(msgstat))
tx_t = time.time()
sertx.write(msg.encode())
tx_t=str(tx_t)
s.send(tx_t.encode())
s.close()
time.sleep(0.001)
Error - File ".\tx.py", line 23, in
s.send(tx_t.encode())
OSError: [WinError 10038] An operation was attempted on something that is not a socket
PS C:\Users\ambuj\Documents\Python Scripts>
Server
import socket
s = socket.socket()
port = 43470 # make this any random port
s.bind(('127.0.0.1', port))
s.listen(5) # put the socket into listen mode
while True:
c, addr = s.accept()
data = c.recv(1024).decode("utf-8") # This data is received from the client script
print(data)
c.close()
You can surely achieve this thing using socket communication. Just create a server script like this which will listen to any incoming data to a specific port...
import socket
s = socket.socket()
port = 43470 # make this any random port
s.bind(('127.0.0.1', port))
s.listen(5) # put the socket into listen mode
while True:
c, addr = s.accept()
data = c.recv(1024).decode("utf-8") # This data is received from the client script
c.close()
Now in your client script, you have to connect to the socket that is binded in that port. Make a client script like this...
import socket
s = socket.socket()
port = 43470 # Use the same port number here as you did in the server script.
s.connect(('127.0.0.1', port))
s.send(b"This data will be received by the server!")
s.close()
You can do the reverse as well. So the server will be able to send the data to the client script. Its a two-way communication.
Remeber: This is just a simple demonstraction to make things work. In actual case, modification is much needed.
I am having the above issue. The client is suppose to ask for a filename and send the file name to the server after which the server will open the file and display it. Problem is that the server isn't opening the file and displaying it.
Below is the client.
#!/usr/bin/env python3
import socket, os.path, datetime, sys
def Main():
host = '127.0.0.1'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = input("Type in ur file ")
s.send(Filename.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
s.close()
if __name__ == '__main__':
Main()
Below is the server
#!/usr/bin/env python3
import socket
import os
import sys
def Main():
host = '127.0.0.1'
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
c, addr = s.accept()
print("Connection from: " + str(addr))
while True:
data = c.recv(1024).decode('utf-8')
myfile = open(data, "r")
if not data:
break
print("from connected user: " + myfile)
c.close()
if __name__ == '__main__':
Main()
I've made few minimal adjustments to your code with which it runs as so that server.py continuously listens on a given port and sends back data which each invocation of client.py asks for.
server.py
#!/usr/bin/env python3
import socket
import os
import sys
def Main():
host = '127.0.0.1'
port = 50001
s = socket.socket()
s.bind((host,port))
print("server Started")
s.listen(1)
while True:
c, addr = s.accept()
print("Connection from: " + str(addr))
filename = ''
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
filename += data
print("from connected user: " + filename)
myfile = open(filename, "rb")
c.send(myfile.read())
c.close()
if __name__ == '__main__':
Main()
client.py
#!/usr/bin/env python3
import socket, os.path, datetime, sys
def Main():
host = '127.0.0.1'
port = 50001
s = socket.socket()
s.connect((host, port))
Filename = input("Type in ur file ")
s.send(Filename.encode('utf-8'))
s.shutdown(socket.SHUT_WR)
data = s.recv(1024).decode('utf-8')
print(data)
s.close()
if __name__ == '__main__':
Main()
And now a bit of explanation.
On the server side. The outer loop accepts a connection, then reads from the connection until done (more on this later). Prints your debugging info, but note you were trying to print the file object and not the filename (which would fail trying to concatenate). I also open the file in binary mode (that way I can skip the str -> bytes translation.
On the client side. I've added closing the writing end of the socket when the file has been sent. Note you might want to use sendall instead of send for this use case: check those docs links for details. And I've added a print for the incoming data.
Now that bit with shutting down the writing end in the client and the inner loop reading (and also related to the sendall hint. Which BTW also holds true for the server side, otherwise you should loop, as you might see your content truncated; other option is to also have a sending loop.). Stream sockets will guarantee you get your bytes in in order you've send them. On itself it has no idea whether your message is complete and it also does not guarantee in how many and how large chunks will the data be sent and received (resp.).
The inner loop of server keep reading until we see an EOF (we've receive zero length string in python socket). This would happen (be returned by recv when the remote socket (or at least its writing end) has been shut down. Since we still want to reuse the connection, we only do that on the sending end in the client. Hope this helps you to move ahead.
I have a program that scans for open ports on remote host.
It will take long time to complete the scan.I want to make it work fast.
Here's my code:
Port Scan
import socket
import subprocess
host = input("Enter a remote host to scan: ")
hostIP = socket.gethostbyname(host)
print("Please wait, scanning remote host", hostIP)
try:
for port in range(1,1024):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostIP, port))
if result == 0:
print("Port: \t Open".format(port))
sock.close()
Could one of you Python wizards help me with this.
Advance Thanks.
You can set a timeout on the socket so it wont spend to much time on a closed port. I would also use threads and allow the user to specify how many threads they want to run. here is a link to some code you could adapt to implement threading with the threading module Python Network Programming.
#!/usr/bin/env python
'''
A simple port scanner.
'''
import socket
def scan_host(host, **options):
'''
Scan a host for open ports.
'''
options.setdefault('timeout', 0.30)
options.setdefault('port_range', (1, 1024))
timeout = options.get('timeout')
port_range = options.get('port_range')
host_ip = socket.gethostbyname(host)
print("Please wait, scanning remote host {} : {}".format(host, host_ip))
for port in xrange(*port_range):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host_ip, port))
if result == 0:
print "Port: {} Open".format(port)
sock.close()
if __name__ == '__main__':
scan_host('www.google.com', timeout=0.30, port_range=(1, 8000))
This program became too simple. It monitors only one port at once and it takes long time on one port to see if it is listening. So try reducing the time to listen, if it can't connect, deem it to be closed by setting a recursion limit for that number under the "expect:" in run().
As in like this,
try:
# connect to the given host:port
result = sock.connect_ex((hostIP, port))
if result == 0:
print "%s:%d Open" % (hostIP, port)
sock.close()
except: #pass
sock.recurse += 1
if sock.recurse < sock.limit:
sock.run()
else:
print "%s:%d Closed" % (hostIP, port)
There is other way to make it much more efficient by importing threading() module which can be used to keep an eye on a large number of sockets at once.
Here's the document on threading.
Refer this,
https://docs.python.org/2/library/threading.html#
Hope that helped you.
All the best.
I am trying to make a simple LAN instant messager where many clients connect to the server and the server replies back and can see what the client is saying. I have tried but my lack of knowledge using the threading module has limited me. At the moment, however, the server only gets a message and has to reply to get the next one. I am trying to make it so the server can see all the messages it receives instantly and can reply whenever he need to. How?
Server Code:
from threading import *
import socket
s = socket.socket()
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)
def getMainThread():
for thread in enumerate(): # Imported from threading
if thread.name == 'MainThread':
return thread
if thread.name == 'Thread':
return thread
return None
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.socket = socket
self.address = address
self.start() # Initated the thread, this calls run()
def reply(self):
reply = getThread()
while reply and reply.isAlive():
sent = input("Enter Message: ")
self.socket.send(bytes(sent, 'UTF-8'))
def run(self):
main = getMainThread()
while main and main.isAlive():
message = self.socket.recv(8192).decode('utf-8')
self.socket.send(b"Got your message.. send another one!")
print('Someone:',message)
sent = input("Enter Message: ")
self.socket.send(bytes(sent, 'UTF-8'))
self.socket.close()
while True:
c, addr = s.accept()
client(c, addr)
Client Code:
import socket
host = socket.gethostbyname(socket.gethostname())
print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))
#host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))
sock = socket.socket()
try:
sock.connect((host, 1337))
while True:
message = input("Enter Message: ")
if message == 'quit':
break
sock.send(bytes(message, 'UTF-8'))
recieved = sock.recv(8192).decode('utf-8')
print('Server responded with:', recieved)
except socket.error:
print ("Host is unreachable")
sock.close()
Also, is it possible using Threading so that 2 while statements can run at the same time? If so, can someone give me an example?
Boosting this to try and get an answer. Anyone?
I am currently working on a server in Python, the problem I am facing is the client could not retrieve the sent data from server.
The code of the server is:
import sys
import socket
from threading import Thread
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(1024)
print rm
try:
self.sockfd.sendall("\n Test text to check send.")
print "Data send successfull"
break
except socket.error, e:
print "Could not send data"
break
except ValueError:
self.sockfd.send("\n Could not connect properly")
def run(self):
self.newClientConnect()
self.sockfd.close()
while True:
buff = self.sockfd.recv(1024)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '127.0.0.1'
PORT = 80
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
print ("Server Started")
try:
serversocket.bind(('',5000))
except ValueError,e:
print e
serversocket.listen(5)
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
#--
And the client connecting is:
import socket
HOST = '192.168.1.4' # The remote host
PORT = 5000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
print 'Received', data#repr(data)
In need of a quick solution....
Thanks,
I tested out your code, and when I commented out
rm= self.sockfd.recv(1024)
print rm
it worked fine. Basically the server stopped there to wait for a message that never came. If it still does not work for you, there might be two problems. Either you have a firewall that blocks the connection somehow, or you have old servers running in the background from previous tries that actually wasn't killed. Check your processes if pythonw.exe or equivalent is running when it shouldn't be, and kill it.
To wait for response:
with s.makefile('rb') as f:
data = f.read() # block until the whole response is read
s.close()
There are multiple issues in your code:
nested while True without break
finally: ..close() is executed before except ValueError: ..send
multiple self.sockfd.close()
etc
Also you should probably use .sendall() instead of .send().
your server code is excepting client send something first,
rm= self.sockfd.recv(1024)
but I don't see any in your code
please try send something in your client code
s.connect((HOST, PORT))
s.send("hello")
Short solution
Add a short sleep after connect.
import time
time.sleep(3)