need some help on looping the all the list and print the list name
currently i have few raspberry pi type and windows PC, i want to ping all the pi and windows and get respond
below are some of what i have tried
question is how to loop, piserver, pi2b,pi2,pi3,pi4 and windows
import platform
plat = platform.system()
piservers = {"10.10.10.115", "10.10.10.125", "10.10.10.135", "10.10.10.145", "10.10.10.165", "10.10.10.175", "10.10.10.185"}
pi2b= {"10.10.10.111", "10.10.10.112", "10.10.10.113", "10.10.10.114"}
pi2 = {"10.10.10.121", "10.10.10.122", "10.10.10.123", "10.10.10.124"}
pi3 = {"10.10.10.131", "10.10.10.132", "10.10.10.133", "10.10.10.134"}
pi4 = {"10.10.10.141", "10.10.10.142", "10.10.10.143", "10.10.10.144"}
Windows = {"10.10.10.151", "10.10.10.152", "10.10.10.153", "10.10.10.154"}
for vm in piservers :
# Check for Windows and Linux Platforms
if plat == "Windows":
response = os.system("ping -n 1 " + vm)
pass
elif plat == "Linux":
response = os.system("ping -c 1 -W 3 " + vm)
pass
#and then check the response...
if response == 0:
print ("***********************************")
print(vm, 'is UP!')
print ("***********************************")
print ("\n")
elif response == 2 or 256 or 512:
print ("***********************************")
print(vm, 'is DOWN and No response from Server!')
print ("***********************************")
print ("\n")
else:
print ("***********************************")
print(vm, 'is DOWN!')
print ("***********************************")
print ("\n")
If you want to loop through all the sets at once, you can do:
for vm in piservers|pi2b|pi2|pi3|pi4|Windows:
Update
To get the server list name, write a function like this:
def get_server(ip):
servers = ['piservers', 'pi2b', 'pi2', 'pi3', 'pi4', 'Windows']
for server in servers:
if ip in eval(server):
return server
return ''
Use this function where ever you need to show the list name.
for example:
get_server('10.10.10.151')
'Windows'
get_server('10.10.10.133')
'pi3'
In your case, the code will look like this,
get_server(vm)
In your elif statement, it should be:
elif response == 2 or response == 256 or response == 512:
Related
So I've been trying to understand how this code works using Scapy on Python as I am trying to create a similar traceroute for my project. However, this does not work. I tried printing the reply type and it shows '11' in between hops. Does anyone have any suggestions on how to fix this or does this whole thing just not work?
hostname = "172.217.17.46" #Change that to user input later
print("Destination: " + hostname)
for i in range(1,28):
pkt = IP(dst=hostname, ttl=i)/ UDP(dport=33434)
#packet is sent
reply = sr1(pkt, verbose=0)
#print(reply.type)
#No reply
if reply is None:
print("hi")
break
elif reply.type == 3:
#reached
print("Done", reply.src)
break
#continue
else:
#print(reply.type)
print ("%d hops away: " %i, reply.src)
#continue
break
I have the following piece of Python 2.7 code:
def getGateway():
""" Use the configuration to determine valid gateway
If more GWs are present, one will be chosen by random.choice
"""
localServer = ThisLocalServer(log=LOG)
gw=localServer.getRandomAgentGateway()
print "See if its a string %s - %s" % (gw,type(gw))
candidate = "gw"
response = os.system("ping -c 1 " + candidate)
if response == 0:
print candidate, 'is up!'
return gw
else:
print candidate, 'is down we need a new gatewuy'
The use case is as follows:
My software determines an IP using getRandomAgentGateway. Unfortunately it is not as inteligent as i want it to be and sometimes the result is an unreachable IP. I want to build in a ping check that will :
A) Get one IP ( there are only two in the list ) using the already built in getRandomAgentGateway
B) Ping the IP
C) Make sure this IP is reachable , if yes - deliver a reachable IP, break out of the loop and execute "return gw" , if not - stay in the loop and call "getRandomAgentGateway()" again until it finds a reachable IP
I cannot modify getRandomAgentGateway, so i would like to build the ping check here. Any assistance will be highly appreciated.
It seems that you have an error in your logic.
candidate = "gw"
seems to be doing the wrong thing. What you need is probably
if isinstance(gw,str):
# do whatever
Actually, why getRandomAgentGateway will return other answer than an str?
Finally, for this to work you probably should try more than one time, writing something like:
def teste():
max_number_of_tries = 2
current_try = 0
while current_try < max_number_of_tries:
gw=getRandomAgentGateway()
if isinstance(gw,str):
response = os.system("ping " + gw)
if response == 0:
print( gw, 'is up!')
return gw
else:
print( gw, 'is down we need a new gatewuy, trying again')
current_try += 1
print ( "Too much tries" )
I am trying pjsip with Python 2.7.3 in CentOS, Fedora, ArchLinux, Ubuntu to have
- sip registration
- sip audio codec encode/decode
- media access microphone, speaker out
- networking stun, turn
Till now i have written this following code, it works to register sip, place call stay connected.
But problem is i cant capture microphone and listen audio in speaker which is failing. So i was searching for some stable working sample if there is any. Can anyone please advise?
import sys
import pjsua as pj
LOG_LEVEL=3
current_call = None
def log_cb(level, str, len):
print str,
class MyAccountCallback(pj.AccountCallback):
def __init__(self, account=None):
pj.AccountCallback.__init__(self, account)
# Notification on incoming call
def on_incoming_call(self, call):
global current_call
if current_call:
call.answer(486, "Busy")
return
print "Incoming call from ", call.info().remote_uri
print "Press 'a' to answer"
current_call = call
call_cb = MyCallCallback(current_call)
current_call.set_callback(call_cb)
current_call.answer(180)
# Callback to receive events from Call
class MyCallCallback(pj.CallCallback):
def __init__(self, call=None):
pj.CallCallback.__init__(self, call)
# Notification when call state has changed
def on_state(self):
global current_call
print "Call with", self.call.info().remote_uri,
print "is", self.call.info().state_text,
print "last code =", self.call.info().last_code,
print "(" + self.call.info().last_reason + ")"
if self.call.info().state == pj.CallState.DISCONNECTED:
current_call = None
print 'Current call is', current_call
# Notification when call's media state has changed.
def on_media_state(self):
if self.call.info().media_state == pj.MediaState.ACTIVE:
# Connect the call to sound device
call_slot = self.call.info().conf_slot
pj.Lib.instance().conf_connect(call_slot, 0)
pj.Lib.instance().conf_connect(0, call_slot)
print "Media is now active"
else:
print "Media is inactive"
# Function to make call
def make_call(uri):
try:
print "Making call to", uri
return acc.make_call(uri, cb=MyCallCallback())
except pj.Error, e:
print "Exception: " + str(e)
return None
# Create library instance
lib = pj.Lib()
try:
# Init library with default config and some customized
# logging config.
lib.init(log_cfg = pj.LogConfig(level=LOG_LEVEL, callback=log_cb))
# Create UDP transport which listens to any available port
transport = lib.create_transport(pj.TransportType.UDP,
pj.TransportConfig(0))
print "\nListening on", transport.info().host,
print "port", transport.info().port, "\n"
# Start the library
lib.start()
# when no sound card found
lib.set_null_snd_dev() # here is the problem i cant capture mic, speaker from local system
# Create local account
#acc = lib.create_account_for_transport(transport, cb=MyAccountCallback())
acc = lib.create_account(pj.AccountConfig("192.168.1.12", "abc", "admin2013"))
cb = MyAccountCallback(acc)
acc.set_callback(cb)
#cb.wait()
print "\n"
print "Registration complete, status=", acc.info().reg_status, \
"(" + acc.info().reg_reason + ")"
# If argument is specified then make call to the URI
if len(sys.argv) > 1:
lck = lib.auto_lock()
current_call = make_call(sys.argv[1])
print 'Current call is', current_call
del lck
my_sip_uri = "sip:" + transport.info().host + \
":" + str(transport.info().port)
# Menu loop
while True:
print "My SIP URI is", my_sip_uri
print "Menu: m=make call, h=hangup call, a=answer call, q=quit"
input = sys.stdin.readline().rstrip("\r\n")
if input == "m":
if current_call:
print "Already have another call"
continue
print "Enter destination URI to call: ",
input = sys.stdin.readline().rstrip("\r\n")
if input == "":
continue
lck = lib.auto_lock()
current_call = make_call(input)
del lck
elif input == "h":
if not current_call:
print "There is no call"
continue
current_call.hangup()
elif input == "a":
if not current_call:
print "There is no call"
continue
current_call.answer(200)
elif input == "q":
break
# Shutdown the library
transport = None
acc.delete()
acc = None
lib.destroy()
lib = None
except pj.Error, e:
print "Exception: " + str(e)
lib.destroy()
lib = None
Your audio problem is related to what I explained in: C - how to resolve this error while using pjsip?. With this, you should be able to properly establish calls.
On the other hand, about a project using pjsip with python, I can only recall python-sipsimple, but I don't have much experience with it.
Hope this helps.
I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)
So I've got a program that will ssh on to a remote server and start an iperf sever of that end.
When thats running it will iperf that sever from the client side.
It works fine when I give the IP address statically for example:
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 ' + iperf)
But not when I use:
p=pexpect.spawn('ssh -t -x paddy#'+ADDRESS+' ' + iperf)
I get a:
'pexpect.TIMEOUT'
ADDRESS is definitely going in correctly.
Any one have any ideas about whats going wrong?
#!/usr/bin/env python
import pexpect
import re
import shutil
import getpass
import struct, fcntl, os, sys, signal, time
def start_Server(iperf, password, ADDRESS):
ssh_newkey = 'Are you sure you want to continue connecting'
fix = ADDRESS+' ' + iperf
p=pexpect.spawn('ssh -t -x paddy#'+ fix)
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
pwtp = False
trysout = True
while pwtp == False:
trysout = True
p.sendline(password)
loginStuff=p.expect(['Permission denied, please try again.','Permission denied (publickey,password).', '------------------------------------------------------------', pexpect.TIMEOUT,pexpect.EOF],1)
if loginStuff == 0:
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
elif loginStuff == 1:
print 'Sorry but you faild to login'
sys.exit(0)
pwtp = True
trysout = False
elif loginStuff == 2:
pwtp = True
i=3
elif loginStuff == 4:
pwtp = True
pass
else:
pass
elif i==2:
print "I either got key or connection timeout"
pass
elif i==4:
print "I either got key or connection timeout"
pass
if i==3: #timeout
print fix
print ADDRESS
print 'we find outselfs in a timeout'
print i
pass
return p, password
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
var = raw_input("Enter the destination IP address: ")
ADDRESS = var
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
t, password = start_Server('iperf -s', password, ADDRESS)
u, password = start_Server('iperf -u -s', password, ADDRESS)
print ADDRESS
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 iperf -u -s')
ssh_newkey = 'Are you sure you want to continue connecting'
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i == 0:
print ssh_newkey
elif i == 1:
print 'password:'
elif i == 2:
print pexpect.EOF
else:
print 'Sorry what!?'
print i
It worked when I took the pexpect ssh out of the subroutine.