Python: ping a certain IP without console window and with UI - python

Is there a way for Python to send ping and get results, 1 or 0, without the console popping out? I need the results for UI change in style.
I've been trying import os and it still shows the console, as well as subprocess.
This is the sample I get from other questions but I can't get the console not to show.
import os
hostname = "google.com"
response = os.system("ping-c 1 " + hostname)
if response == 0:
print hostname, 'is up!'
else:
print hostname, 'is down!'
Thanks for the help.

Related

Python Port Scanner Not Showing Open Ports

I'm following a Python tut on writing a port scanner, it runs, but it seemed to skip over a port that should theoretically be open. I'm running a web browser so port 80 should be up, but when I ran it against my network it just skipped over it. Also tried it against 443, but it's not showing any HTTPS ports either.
import sys #allows us to enter cmd line arguments & other things
import socket #Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC).
from datetime import datetime
#next we need to define our target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #translate host name to IPV4
else:
print (“invald amt of arguments.”)
print (“syntax: python3 scanner.py <ip>”)
sys.exit()
#add a pretty banner
print (“-” * 50)
print (“scanning target” + target)
print(“Time started: “ +str(datetime.now()))
print (“-” * 50)
try:
for port in range (50,85):
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1) #is a float
result = s.connect_ex((target,port)) #returns error indicator
print ((“checking port {}”).format(port)) #returns error indicator
if result ==0:
print (“port {} is open”.format(port))
s.close()
except KeyboardInterrupt:
(“\Exiting Program”)
sys.exit()
except socket.gaierror:
print (“host name could not be resolved”)
sys.exit()
except socket.error:
print (“could not connect to server”)
sys.exit()**
If You replace all smart quoutes with straight quoutes,
indent the TRUE-block of the if-statement inside the for-loop and
remove the escape character ("\") in the exception handler,
then Your code runs fine.

Error when making a socket chat

I am making a chat using the socket library in python, it works, only half way though, when you netcat onto what I am using as a channel I am able to send messages and the other terminal is able to receive them, but, when that terminal sends a message (typing text, then hit enter) I do not receive it through the python script. So I ran it raw in the following way:
python shell:
import socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(("127.0.0.1",8000)
sock.listen(2)
(client, (ip,port))=sock.accept()
Terminal:
nc 127.0.0.1 8000
This worked and to send or receive in the python shell all I had to do was type: sock.send("message") or sock.recv(2012)
Here is My code:
#!/bin/python
import socket
import subprocess
from subprocess import Popen, PIPE
import time
class color:
r = '\033[31m'
g = '\033[32m'
d = '\033[0m'
b = '\033[94m'
p = '\033[35m'
def clear():
print('\n' * 100)
chat_clients = []
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clear()
def chatting_on_serverr():
(client, (ip, port))=sock.accept()
def chatting_on_server():
message = raw_input("Send Message: ")
client.send(message + '\n')
client.recv(2012)
chatting_on_server()
chatting_on_server()
def make_channel():
print color.b + '[+] '+color.d+'Welcome to the chat server'+color.b+' [+]'
host = raw_input("Channel Name: ")
port = input("Channel Access Key: ")
clear()
print color.p + "[info] "+color.b+"Making %s" % host
time.sleep(1)
sock.bind((host,port))
sock.listen(3)
print color.g + "[+] "+color.d+"Channel Made"+color.g+" [+]"+color.d
print("[info]: Waiting for people to join your channel...")
global chatting_on_serverr
global chatting_on_server
chatting_on_serverr()
clear()
make_channel()
I cannot reproduce this on my machine because of network limitations but I recommend you to look at this tutorial of a Python chat client and server. It will explain a lot about sockets and networking.
Beside that you shouldn't define globals with the same name as functions in your code. It might override their declaration. Another thing is the function inside the function. You can write that function like that:
def chatting_on_server():
client, (ip, port) = sock.accept()
while True:
message = raw_input("Send Message: ")
client.send(message + '\n')
client.recv(2012)
And you will get the same functionality. Also, you risk yourself with a stack overflow error because chatting_on_server calls itself forever.
Good luck!
All that was needed to be done is to print the output of the .recv function
x = client.recv(2020)
print(x)

print tn.read_all() does not return anything in telnetlib python script

I am trying to telnet into a cisco ios-xr router and gather command output.
I have tested that the below code successfully connects to the router and executes the command, however it seems that neither print tn.read_all() nor tn.read_very_eager() works. They do not print anything. Am I missing anything obvious here?
#!/usr/bin/env python
import sys
import telnetlib
import time
HOST = "10.62.53.34"
PORT = "17006"
user = "cisco"
password = "cisco"
tn = telnetlib.Telnet(HOST,PORT)
print "Telnetting to", HOST, "#",PORT
tn.write("\n")
tn.write(user + "\n")
tn.write(password + "\n")
#print("I am in")
tn.write("show runn\n")
tn.write("exit \n")
print tn.read_all()
tn.close()
though this question is from february, i'll post my answer for a potential future googler.
i fixed a similar problem when i realized that:
print tn.read_all()
...is valid in python 2 (see the example at the bottom of https://docs.python.org/2/library/telnetlib.html), but not in python 3 (https://docs.python.org/3.6/library/telnetlib.html).
for python 3, the correct syntax would be:
print(tn.read_all())

How to telnet and collect logs, Whenever the IP is alive/active?

PING:
import os
ip=1.1.1.1
o=os.system("ping "+ip)
time.sleep(10)
print(o)
if res == 0:
print(ip,"is active")
Telnet:
tn = telnetlib.Telnet(IP)
tn.write(command+"\r\n")
f=open(filename,w)
while True:
response = tn.read_until("\n")
f.write(response)
Here, In between IP goes down. During that time i need to ping that IP & whenever it comes up i need to start collecting logs again. How can i do this ?
Actually, I need to collect logs through telnet (which is indefinite). I could able to do it. During this process, IP from which i'm collecting logs goes down. So, I need to track on this IP (Ping). Whenever IP comes up again, I've to start collecting the logs again. It would be great, if you can help me on this.
I found the solution:
tn=telnetlib.Telnet(IP)
tn.write(command+"\r\n")
f=open(filename,w)
while (os.system("ping -n 1 IP") == 0):
response = tn.read_until("\n")
f.write(response)
else:
call some module for telnetting again/goto
But, here is it possible to hide the console when we use (os.system(ping)). I know it can be done through subprocess. But since os.system is a one liner & very easy to verifY the result also.
Maybe pexpect is what you're looking for?
This snippet will start a ping process, and block until it sees the output "bytes from" or until it times out (1 minute by default):
import pexpect
def wait_until_online(host, timeout=60):
child = pexpect.spawn("ping %s" % host)
child.expect("bytes from", timeout)

Continuous check for VPN Connectivity - Python

Is there any efficient way to check and report in a log file or on the console may be... when ever the VPN is disconnected?
import time
print time.asctime( time.localtime(time.time()) )
Can print the time but I do not know what is the code to recursively find whether the VPN is active or not. Pinging it in a while(1) would be a stupid way to check if the connection is active or not. Any way to achieve this?
This solution is system dependent, I do know that it works on Linux because I've done something similar, but not sure about Windows though. I don't know if you want a solution not involving ping, but I think this is a good solution.
import logging, os, time
PING_HOST='10.10.10.10' # some host on the other side of the VPN
while True:
retcode = os.system('ping -c 1 %s' % PING_HOST)
if retcode:
# perform action for lost connection
logging.warn('Lost visibility with %s' % PING_HOST)
time.sleep(10) # sleep 10 seconds
This works because ping returns a return code of 0 for success. All other return codes signify an error.
In case the IP of vpn changes, you can check if a tunnel has been established at all.
import psutil
import logging, os, time
import subprocess
import sys
procname = "yourprocess_name"
while True:
cmdout = subprocess.Popen(["ifconfig | grep tun"],stdout = subprocess.PIPE, shell=True).communicate()[0]
print "cmdout: "+str(cmdout)
time.sleep(2)
#-----
if "tun" in cmdout:
print "seems to be ok"
if not "tun" in cmdout:
# perform action for lost connection
print "killing "+str(procname)
for proc in psutil.process_iter():
# check whether the process name matches
print "Listing procname: "+str(proc.name())
if proc.name() == procname:
proc.kill()
sys.exit()
This method uses the NAME of the HOST "Connection-specific DNS Suffix" associated with your IP (Mostly the corporation's VPN):
import os
import platform
def check_ping():
hostname = "xyz.com" #hostname will be..Name under: "Connection-specific DNS Suffix" when you type "ipconfig" in cmd..
response = os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active: Connected"
else:
pingstatus = "Network Error: Not Connected"
return pingstatus
response = check_ping()
print(response)

Categories

Resources