I would like to add the flag
-c 4
to my line of code at
hostname = "216.58.223.3 -c 4"
The way it currently works:
#staticmethod
def valve_southafrica_two():
print("Pinging Valve South Africa 2")
hostname = "155.133.238.163"
response = os.system("ping " + hostname)
if response == 0:
pingstatus = "Active"
else:
pingstatus = "Error"
print("Ping Test Complete")
return pingstatus
and the way I want it to work is so:
#staticmethod
def valve_southafrica_two():
print("Pinging Valve South Africa 2")
hostname = "155.133.238.163 -c 4"
response = os.system("ping " + hostname)
if response == 0:
pingstatus = "Active"
else:
pingstatus = "Error"
print("Ping Test Complete")
return pingstatus
for Linux +/ MacOS Pinging, is there any way to bulk add the -c 4 flag next to the xxx.xxx.xxx.xxx (IP) or is the only solution to manually add the -c 4 next to each line?
Use subprocess,call
By which we can send the commands as a list of arguments so we just need to specify -c 4 as an argument
import subprocess
#import os
def valve_southafrica_two():
print("Pinging Valve South Africa 2")
hostname = "155.133.238.163"
response =subprocess.call(["ping",hostname,"-c 4"])
if response == 0:
pingstatus = "Active"
else:
pingstatus = "Error"
print("Ping Test Complete")
return pingstatus
valve_southafrica_two()
OUTPUT
Pinging Valve South Africa 2
PING 155.133.238.163 (155.133.238.163) 56(84) bytes of data.
64 bytes from 155.133.238.163: icmp_seq=1 ttl=47 time=327 ms
64 bytes from 155.133.238.163: icmp_seq=2 ttl=47 time=325 ms
64 bytes from 155.133.238.163: icmp_seq=3 ttl=47 time=326 ms
64 bytes from 155.133.238.163: icmp_seq=4 ttl=47 time=325 ms
--- 155.133.238.163 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
rtt min/avg/max/mdev = 325.113/326.192/327.601/0.992 ms
Ping Test Complete
You can use string formatting or f-strings like below
flag = '-c 4'
# python 3.6
hostname = f'155.133.238.163 {flag}'
# python 2.7
hostname = '155.133.238.163 {0}'.format(flag)
Output
155.133.238.163 -c 4
Related
I tried pinging multiple servers using hostname, without extra .txt file.
I'm trying like this..
import os
for i in range(1,2): #`for i in range(1,2):
hostname1= "google.con" # example
hostname2 = "google.com" # example
response = os.system("ping -n 1 " + hostname1)
response = os.system("ping -n 1 " + hostname2)
and then check the response...
if response == 0:
flag = 'OK'
else:
flag = 'KO'
if flag == 'OK':
print('all hosts are up!')
else:
print('something is wrong')
I'm new to Python and PyCharm.
Please, correct me, in case of any fundamental mistakes.
NKalyan
Your code makes no sense. Especially your for-loop
You should keep hosts on list and use for-loop to work with every host separatelly.
You can't assign response many times because it will remove previous value and you will check only last result.
import os
# --- before loop ---
hostnames = ["google.con", "google.com", "stackoverflow.com"]
all_ok = True # at start I assume that all hosts are OK
# --- loop ---
for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
all_ok = False # one of host is down
# don't use `else: all_ok = True`
# --- after loop ---
if all_ok:
print('all hosts are up!')
else:
print('something is wrong')
Similar way you can count hosts with problems
import os
# --- before loop ---
hostnames = ["google.con", "google.com", "stackoverflow.com"]
count = 0
# --- loop ---
for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
count += 1 # one of host is down
# --- after loop ---
if count == 0:
print('all hosts are up!')
else:
print('number of down hosts:', count)
or you can use list for hosts with problems
import os
# --- before loop ---
hostnames = ["google.con", "google.com", "stackoverflow.com"]
problems = [] # hosts with problems
# --- loop ---
for host in hostnames:
response = os.system("ping -n 1 " + host)
if response != 0:
problems.append(host) # one of host is down
# --- after loop ---
if not problems: # if len(problems) == 0:
print('all hosts are up!')
else:
print('number of downed hosts:', len(problems))
print('hosts:', problems)
What i want to achieve would be reading the IP/Domain from the TXT file and executing an OS import command then adding the IP/Domain when pinging.
However the problem is that for some reason it's placing a period at the end of the IP/Domain that it read from the TXT file, resulting in an invalid request when pining (the code works the only problem would be the period at the end)
for example: when the pinging line executes on the compiler it's telling me "bad parameters google.com." however on the txt file it self there is only one period which is the one for the .com it self.
def scanlist():
ipopen = open("IPlist.txt")
#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
with open("IPlist.txt", "r+") as ips_file:
ips = [ip.strip() for ip in ips_file.readlines()]
#Read each line from the IPlist.txt file
with open("IPlist.txt", "r") as available_ips_file:
for ip in ips:
#Pings each line from the IPlist.txt file
response = os.system('ping -a 1 {}'.format(ip))
if response == 0: # 512/DOWN value - 0/UP value
# Up
print("- Ip Address:", ip, 'is up!')
elif response == 512:
#down
print("- IP Address:", ip, 'is down!')
else:
#other error
print("- Bad parameters or other error!")
For the entire code visit the github: https://github.com/Hontiris1/IPPing/blob/master/Ping.py
the issue was in the paramter you were passing to the ping the 1 after -a is not a valid parameter
import os
def scanlist():
#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
with open("IPlist.txt") as ips_file:
ips = list(map(str.strip,ips_file.readlines()))
#Read each line from the IPlist.txt file
for ip in ips:
#Pings each line from the IPlist.txt file
response = os.system('ping {} -a -n 1'.format(ip)) # to send only one request
if response == 0: # 512/DOWN value - 0/UP value
# Up
print("- Ip Address:", ip, 'is up!')
elif response == 1: # if it's time out
#down
print("- IP Address:", ip, 'is down!')
else:
#other error
print("- Bad parameters or other error!")
scanlist()
output
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=55ms TTL=56
Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 55ms, Maximum = 55ms, Average = 55ms
- Ip Address: 8.8.8.8 is up!
Pinging stackoverflowll.com [218.93.250.18] with 32 bytes of data:
Request timed out.
Ping statistics for 218.93.250.18:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
- IP Address: stackoverflowll.com is down!
I am trying to write a script to print a ping check to the browser with 5 pings.
This script:
from bottle import route, run, template
import subprocess
#route('/pings/<ip>')
def ping(ip):
param = '-c 1'
command = ['ping', param, ip]
num = 0
while (num < 6):
return subprocess.check_output(command)
num += 1
run(host='0.0.0.0', port=8080)
Currently outputs to the browser as follows:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8:
icmp_seq=1 ttl=54 time=17.7 ms --- 8.8.8.8 ping statistics --- 1
packets transmitted, 1 received, 0% packet loss, time 0ms rtt
min/avg/max/mdev = 17.756/17.756/17.756/0.000 ms
But it doesn't print out 5 pings like I expect it to. It only prints out the one ping, is it for some reason only printing out the last one? How can I print out 5 pings like it would look if you ran it from a shell command.
Thanks.
The loop is only running once because return is executed during the first iteration of the loop therefore you're only getting the first result. You can get the ping result and append that to a list then once the loop is complete you can just return that list.
def ping(ip):
param = '-c 1'
command = ['ping', param, ip]
num = 0
output = []
while (num < 6):
output.append(subprocess.check_output(command))
num += 1
return output // or return "\n".join(output)
When I use this command on Linux, it works:
echo "test.bash.stats 44 1459116000" | nc myhostname.com 2003
But now, I try to implement this command in a Python script.
Method 1: Use os.system("")
# this works
os.system("echo 'test.bash.stats 14 1459116000' | nc myhostname.com 2003")
#It does not work because there are a problem with quote
data['time_timestamp'] = 1459116000
os.system("echo 'test.bash.stats 14 "data['time_timestamp']"' | nc myhostname.com 2003")
Method 2: Use socket
import socket
def netcat(hostname, port, content):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.sendall(content)
s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
if data == "":
break
print "Received:", repr(data)
print "Connection closed."
s.close()
netcat("myhostname.com", 2003, "test.bash.stats 14 1459116000")
I don't get an error, but I don't receive data.
You should try concatenating the string like this
os.system("echo 'test.bash.stats 14 " + str(data['time_timestamp']) + " '| nc myhostname.com 2003")
or this
os.system("echo 'test.bash.stats 14 %d '| nc myhostname.com 2003" % data['time_timestamp'])
I am playing around with a little netcat tool of my own, but I keep getting "Connection refused" and a reference to a specific line, I've highlighted that below.
First I run the server, with the following command:
python Netstatx.py -l -p 9999 -c
Then I run the "client" which tries to make a connection to the server, which is listening on port 9999:
python Netstatx.py -t localhost -p 9999
As mentioned, the above gives me an "Connected refused"-exception, how come?
import sys
import socket
import getopt
import threading
import subprocess
# Define globals
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "Netstatx - Net Tool for your convenience"
print
print "Usage: Netstatx.py -t target_host -p port"
print "-l --listen - Listen on [host]:[port] for
incoming connections"
print "-e --execute=file_to_run - Execute the given file upon
receiving a connection"
print "-c --command - Initialize a command shell"
print "-u --upload=destination - Upon receiving connection,
upload a file and write to
[destination]"
print
print
print "Examples: "
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -c"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -u=\\target.exe"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
sys.exit(0)
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "%s:%s" % (target, port)
# Connect to our target host
**client.connect((target, port))** <-- This is failing.
if len(buffer):
client.send(buffer)
while True:
# Now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print response,
# Wait for more input
buffer = raw_input("")
buffer += "\n"
# Send it off
client.send(buffer)
def server_loop():
global target
# If no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# Spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler,
args=(client_socket,))
client_thread.start()
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# Read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu:",
["help","listen","execute","target","port","command",
"upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled option!"
# Are we going to listen or just send data?
# if not listen and len(target) and port > 0
# Read in the buffer from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
buffer = sys.stdin.read()
# Send data off
client_sender(buffer)
# We are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
main()
def run_command(command):
# trim the newline
command = command.rstrip()
# Run the command and get the output back
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command. \r\n"
# Send the output back to the client return output
return output
def client_handler(client_socket):
global upload
global execute
global command
# Check for upload
if len(upload_destination):
# Read on all of the bytes and write to our destination
file_buffer = ""
# Keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
# Now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
# Acknowledge that we rote the file out
client_socket.send("Successfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# Check for command execution
if len(execute):
# Run the command
output = run_command(execute)
client_socket.send(output)
# Now we go into another loop if a command shell was requested
if command:
while True:
# Show a simple prompt
client_socket.send("<Netstatx:#> ")
# Now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# Send back the command output
response = run_command(cmd_buffer)
# Send back the response
client_socket.send(response)
import sys
import socket
import getopt
import threading
import subprocess
#define some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "Net Tool"
print
print "Usage : netcat.py -t target_host -p port"
print "-l --listen -listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run -execute the given file upon receiving a connection "
print "-c --command -intialize a command shell"
print "-u --upload=destination -upon receiving connection upload a file and write to [destination]"
print
print
print "Examples : "
print "netcat.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "netcat.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEEGHI' | ./netcat.py -t 192.168.11.12 -p 135"
sys.exit(0)
def run_command(command):
#trim the newline
command= command.rstrip()
#run the command get the output back
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command.\r\n"
#send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
#check for upload
if len(upload_destination):
#read in all of the bytes and write to our destination
file_buffer= ""
#keep reading data until none is available
while True:
data= client.socket.recv(1024)
if not data:
break
else:
file_buffer += data
#now we take these bytes and try to write them out
try:
file_descriptor=open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
#aknowledg that we wrote the file out
client_socket.send("Successfully saved file to %s \r\n" % upload_destination)
except:
client_socket.send("Failed to save file to %s \r\n" % upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_buffer)
# send back the response
client_socket.send(response)
def client_sender(buffer):
client= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#connect to our target host
client.connect((target,port))
if len(buffer):
client.send(buffer)
while True:
#now wait for data back
recv_len=1
response=""
while recv_len:
data = client.recv(4096)
recv_len= len(data)
response+=data
if recv_len<4096:
break
print response,
#wait for more input
buffer = raw_input("")
buffer+= "\n"
# send it off
client.send(buffer)
except:
print "[*] Exception! Exiting."
client.close()
def server_loop():
global target
#if no target is defined , we listen on all interfaces
if not len(target):
target ="0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
#spin off a thread to handl our new client
client_thread= threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
#read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l","--listen"):
listen=True
elif o in ("-e", "--execute"):
execute =a
elif o in ("-c", "--commandshell"):
command= True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target =a
elif o in ("-p", "--port"):
port=int(a)
else :
assert False, "unhandled option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port> 0 :
#read in the buffer from the cmdline
#this will block, so send CTRL-D if not sending input
#to stdin
buffer = sys.stdin.read()
client_sender(buffer)
#we are goin to listen and potentially
#upload things, execute commands, and drop a shell back
#depending on our command line options above
if listen :
server_loop()
main()
I found some syntax errors running out your script ( it may be just from copy past), any way i did my small edits and it's working (knowing i'm under linux)
Your problem may be the firewall is refusing connection on that port, try to check it out