I am automating few configuration steps on CentOS. In order to do so i need to reboot the system also. I am invoking the "reboot" command the via python pexepct, however i need to wait till the systems boots up for remaining script to executes. For that i am have written this small piece of code.
while True:
result = commands.getoutput("ping -c 4 192.168.36.134")
if result.find("Unreachable") == 1:
result = False
print 'Rebooting the Systems.'
else:
result = True
print 'Connected!'
break
Is there any better way to do this? Also, can we achieve this with the pexepct itself?
You can try this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# wait host to finish reboot, check specific port connection (usually ssh port if you want to exec remote commands)
while True:
try:
s.connect(('hostname', 22))
print "Port 22 reachable"
break
except socket.error as e:
print "rebooting..."
# continue
s.close()
This example is more effective then using ping
Related
I have this function on a thread running with kivy when i close the app i have to close this socket manually so i can re-run it i tried to socket.SO_REUSEADDR, 1 but it did'nt work and i have this after at end of the code chat_recv_socket.close(). What i want is a more efficient way to kill or end this socket at the except block.
def func_chat_recv_socket():
global chat_recv_string, myip, chat_recv_socket
while True:
if myip != '':
break
while True:
try:
chat_recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
chat_recv_socket.bind((myip, 4600))
chat_recv_socket.listen(10)
while True:
clientsocket, address = chat_recv_socket.accept()
while True:
chat_recv = clientsocket.recv(100)
print('recieving msg')
chat_recv_string = chat_recv.decode("utf-8")
print(chat_recv)
clientsocket.close()
break
except:
### sys or os workaround on android
time.sleep(0.5)
print('binding')
This part was add after
After using this
os.system('freeport 4600')
I am getting this :
Process Type: 'python3' Port: 4600. Kill?[yes/no]
How can u say say from python?
this solution wont work because this command needs to be executed width the sudo. here is the output:
sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
No process running on port 4600 by current user. Checking if root is running the proecess
No process found running on port 4600.
the app has a different behavior on Android, with the catlog from adb android it seems that after closing and opening the app the socket is closed with it, on reopening no error is printed and the socket gets binded as expected. its not a solution but its enough for me right now.
I'm running a port scanner on my home network. If I run it against devices on my home network, it only works on other Linux machines (physical machines not VMs). By "works" I mean it finds what few ports are actually open (ssh, mysql, sunrpc, and a couple others).
When scanning Windows and other miscellaneous iot devices it just hangs and never finishes. I can't seem to figure out where it gets stuck.
I think this might be the most relevant part of the code:
for port in range(begin, end):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
status = s.connect_ex((self.target_ip, port))
except Exception:
continue
finally:
s.close()
if status != 0:
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
I modified your code so that I could simulate a run on my machine and it seems like it hangs because that very last print statement is not reached. But this is because your continue line within the if status != 0 always comes back as "not 0", at least on my Windows 10 Pro machine.
for port in range(begin, end):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
status = s.connect_ex((self.target_ip, port))
print("DEBUG: ", status) # add this
except Exception as err:
print("Error: ", err) # add this
continue
finally:
s.close()
if status != 0:
print("DEBUG: status was not 0") # add this
# if this line is reached, we start at the top of the loop
# skipping the try except and print below entirely.
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
Could you give this a shot and see if will shine some light on what might be wrong or let us know what kind of output you get. I was not able to currently run this on any Linux machine or IoT devices. I assume you are able to read the console output on each of your devices to have determined that it seemed like it was "hanging".
Edit 1: More context for the hanging issue
Let me give you some examples of what happens with this script on my network.
CASE 1: '192.168.1.0'
This address exists, but generally isn't used or assigned to anything. Hangs for about 20 seconds per port for me.
CASE 2: '192.168.1.1'
This is usually the router on the network. Responds immediately. Hangs for about 1 second per port that is scanned.
CASE 3: '192.168.1.3'
This device is in the network range, but no device is actively using it. Hangs for about 20 seconds per port (just like case 1).
So the long "hang" isn't that it is not working. It can basically mean the IP is wrong or there is no device being reached so the timeout limit is being reached for that socket connection attempt instead of raising an exception it just moves on.
Edit 2
Before iterating over a huge range of IP addresses and a wide range of ports per each IP address being tested. Sometimes it can be helpful to test assumptions 1 at a time by defining more control over a few ports and a specific IP address.
This is what I converted your code into to do that. If the conn is not 0 I am just considering that port closed no matter which error code came back for this case. We only care about the ones that respond with 0 because that indicates the operation succeeded.
import socket
# Lets test just a few custom ports.
ports = [21, 22, 80, 8080]
# And test a specific IP address to test, 1 at a time.
ip = '192.168.1.1' # change this if needed
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for port in ports:
# loop through our small custom port range.
try:
conn = sock.connect_ex((ip, port))
if conn == 0:
print("Port [{}] open.".format(port))
else:
print("Port [{}] closed.".format(port))
except Exception as err:
print(err)
continue
try:
service = socket.getservbyport(port)
except Exception:
service = "unknown"
print("SERVICE: %-15s\tPORT: %-8d" % (service, port))
sock.close()
I am trying to create a port scanner in Python. I got the scanner going but it takes forty five minutes to print results. I started to institute threading however I can't figure out how to put different ranges into the script. I started to go to creating a global variable and try to pass that along in each thread. Unfortunately it's not working correctly and I am getting an invalid syntax error. Below is the code.
import socket
import os
import sys
from threading import Thread
server = raw_input("Please enter a server name ")
def portConnect():
global num
try:
serv_ip = socket.gethostbyname(server) # connects to server through try
print "Please wait, scanning remote host", serv_ip
for port in range(num):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = sock.connect_ex((serv_ip, port))
if connect == 0:
print "Port {}: Open".format(port)
sock.close()
except socket.gaierror:
print """
I can't find that server, idiot! Try again
"""
sys.exit()
for i in range(1):
t = Thread(target=portConnect,(num=100))
t.start()
What am I doing wrong?
Thread expects args= as tuple and it sends it as arguments to function
This way you send 100 as first argument (num) to portConnect()
def portConnect(num):
print(num)
# code
t = Thread(target=portConnect, args=(100,) )
To send range you need two arguments
def portConnect(from_, to_):
print(from_, to_)
for port in range(from_, to_):
# ...
size = 20
for i in range(1, 100, size):
t = Thread(target=portConnect, args=(i, i+size))
t.start()
BTW: module scapy lets you send single packet so it is used for portscanning, sniffing, etc.
You can do more with special tools like nmap (GUI wrapper: Zenmap) or Kali Linux
You may try to use nmap in Python: python-nmap : nmap from python
you can solve this really easily using nmap.
nmap -p- <some_host>
import socket
import sys
from datetime import datetime
#Ask the user for input, the form of a remote host entire in the IP address of the target machine
remoteServer =input ("Enter a remote host to scan:")
remoteServerIP =socket.gethostbyname(remoteServer)
#Print a block of text with information on which host we are about to scan.
#While scanning display a message so the user knows the program is working and isn't frozen
print ("_"*60)
print ("Please wait, currently scanning remote host", remoteServerIP)
print ("_"*60)
#Show/check the time scan started
t1 = datetime.now()
#range function to specify ports, this case I have set the pogram to go through ports 1 to 150
# port in range works like so
try:
for port in range (1, 150):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# Press Ctrl C to leave the application
except KeyboardInterrupt:
print ("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print ("Couldn't connect to server")
sys.exit()
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print ('Scanning Completed in: ', total)
My boss has told me to start learning about Metasploitable2 and Kali Linux as such I have attempted to create a port scanner it seems to work fine for most of the part however. after if has finished scanning the ports within it's set range it close completely rather then print ('Scanning Completed in: ', total) with listed findings. What have I done wrong here? And I 'm well aware this is script slow I'm going to attempt to make it multithreaded later on.
Im wondering is there any way to find out the socket that is open and then to close it?
For instance,I have a script "SendInfo.py" which opens a socket and sends some info over TCP.
If I call this script to run it e.g. "python SendInfo.py" , it will open a new socket.
If I run this script again using "python SendInfo.py", which will send some more up to date information, I would like to cancel the previous TCP transaction and start a new one - e.g. by closing the previous socket.
How do I get access to the open socket at the beginning of my script in order to close it? Ive tried looking into threads, but Im similarly confused about which threads are open and how to close open threads etc.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(2)
s.connect((self.__host, PORT))
I'm not sure if this is what you are after but here is a method of ensuring that the script is only running once and killing an existing running script.
You may find something useful in it. (This is for Linux)
#!/usr/bin/python
# running.py
# execute by making the script executable
# put it somewhere on $PATH and execute via running.py
# or execute via ./running.py
import os, sys, time , signal, socket
running_pid = os.popen('ps --no-headers -C running.py').read(5)
try:
running_pid = int(running_pid)
except:
running_pid = 0
current_pid = int(os.getpid())
if running_pid != 0:
if running_pid != current_pid:
print "Already running as process", running_pid
print "Killing process", running_pid
os.kill(int(running_pid), signal.SIGKILL)
# sys.exit()
# Create a listening socket for external requests
tcp_port = 5005
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print "Error on Socket 5005"
# force re-use of the socket if it is in time-out mode after being closed
# other wise we can get bind errors after closing and attempting to start again
# within a minute or so
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.settimeout(0.10)
sock.bind(("localhost", tcp_port))
except IOError as msg:
print "Error on Socket Bind "+str(tcp_port)+", running.py is probably already running"
pass
try:
sock.listen((1))
except:
print "Error on Socket listen"
time.sleep(60)
sock.close()