Hello I need help I write script in python which ping four address ip from dictionary and its works in the loop.when I don’t have response my script do another script at another machine (send message by sms)This script work good, but I would like that if I don't have response to ping that script send me one message with start time and then check available this host after 60 seconds, if still no response then don't send next sms message. But when host recover I would like send me message that this addres ip is available at time (datetime.now) and come back to verify after 60 seconds. What is the better way to do this?
My actual code:
import os
import time
ip = {'1':{'IP':'192.168.1.1','name':'w1'},'2':{'IP':'192.168.1.2','name':'w2'},'3':{'IP':'192.168.1.3','name':'w3'}}
while True:
for cmtsid in ip:
cmts = ip[cmtsid]['name']
ip4 = ip[cmtsid]['IP']
response = os.system('ping -c 5 %s' %ip4)
if response == 0:
print(cmts, 'Available')
else :
try:
os.system('ssh xxxx#1.1.1.1 python /home/user/script.py %s' %cmts)
except Exception as Argument:
f = open("log.txt", "a")
f.write(str(Argument))
f.close()
time.sleep(60)
Related
I am using python to code a program that will ping a device, and do nothing if it gets a response back from the device, but if it does not receive any response, it will send me an email to notify me that the device may be down. However, as has been mentioned on here before, when the response from the ping is "Destination Host Unreachable," the return value is 0, which is the same as if it received a response. So what I'm looking for is help with how to discern the Destination Host Unreachable from the actual response so I can have an email sent to me under that condition (since it means the device is most likely down).
import platform
import subprocess
import smtplib
import time
#Delay to wait for Rigs to Boot
#time.sleep(600)
a = 1
while 1==1:
#Ping other PC's
def myping(host):
parameter = '-n' if platform.system().lower()=='windows' else '-c'
command = ['ping', parameter, '1', host]
response = subprocess.call(command)
if response == 0:
return True
#Will Send email if response from ping is false (aka not pingable/down)
else:
gmail_user = 'email'
gmail_password = 'password'
sent_from = gmail_user
to = ['recepient']
subject = 'subject'
body = 'body'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_password)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print ("Email sent successfully!")
except Exception as ex:
print ("Something went wrong….",ex)
#delay so i dont recieve spam emails while the 'while' loop runs
time.sleep(43000)
print(myping("ip to ping"))
Thank you for the help in advance.
You obviously can't change the behavior of ping. However, you can certainly use subprocess.check_output, which returns the output of the command, and parse that.
Using ping like this is not particularly useful. There are many reasons why you can't reach a remote host. Perhaps your local network is down, or your router has died, or your cable has been unplugged.
I'm trying to create Python TCP client. It is fully functional, but I desire a functionality where if a "connected" message hasn't been recieved from the server for x seconds, then I can close my connection. I currently have a separate thread for recieving messages from the server. Basically, if I receive a message that says "connected" I want to reset a timer.
I've tried a few different approaches to solving it. I've tried to have a separate thread with a timer that keep track of when to disconnect using global variables which is a messy solution which didn't work regardless. I tried to make my own threading subclass but I still was not able to solve the problem and it introduced a lot more complexity than I really need.
a simple approach that I took was to try to have a timer in the while loop in my recieve function. This works for disconnecting from the server, but it will only timeout when a message is sent (due to the try block) and not actually the second the timer is up.
import threading, time, sys
def main():
host = sys.argv[1]
port = sys.argv[2]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host, port)
sock.connect(address)
rec_thread = threading.Thread(target=rec, args=(sock,))
rec_thread.setDaemon(True)
rec_thread.start()
while True:
message = input()
sock.sendall(str.encode(message))
def rec(sock):
start_time = time.time()
while True:
elapsed_time = time.time() - start_time
if(elapsed_time > 10):
sock.close()
try:
msg = sock.recv(1024).decode("utf8")
if msg == 'connected':
start_time = time.time()
else:
print(msg)
except KeyboardInterrupt:
sock.close()
break
If I use this approach then I will only actually close the connection after I recieve a message from the server.
ex: I want it to disconnect immediately after 10s, but if I don't get any message from the server until 14s, then it won't disconnect until 14s.
I'm totally confused as to why my script isn't working.
This script basically scans for servers with port 19 open (CHARGEN).
You enter a list of ips in the format:
1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4
5.5.5.5
and the script scans every ip in the list to check if port 19 is open, and if it is, it writes the ip to a file.
Here is my code:
#!/usr/bin/env python
#CHARGEN Scanner
#Written by Expedient
import sys
import Queue
import socket
import threading
queue = Queue.Queue()
def check_ip(host, output_file, timeout):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((host, 19))
if result == 0:
print "Found: %s" % host
file = open(output_file, "a")
file.write(host+"\n")
file.close()
except:
pass
def add_to_queue(queue, host, output_file, timeout):
queue.put(check_ip(host, output_file, timeout))
if len(sys.argv) < 4:
print "Usage: %s <ip list> <output file> <timeout>" % sys.argv[0]
sys.exit()
try:
open(sys.argv[1])
except:
print "Unable to open ip list."
sys.exit()
print "Starting Expedient's CHARGEN Scanner..."
with open(sys.argv[1]) as ip_list:
for ip in ip_list:
thread = threading.Thread(target=add_to_queue, args=(queue, ip, sys.argv[2], float(sys.argv[3])))
thread.start()
Whenever I run the script on a list of CHARGEN enabled servers that I got from an nmap scan
(I double checked, every server has port 19 open), the script does not write any of the ips
to the output file, which is should, because every ip in the list has port 19 open.
I honestly have no idea why this isn't working and it would be wonderful if someone could
help me out/tell me what I'm doing wrong. Thank you.
Your example as posted is catching all exceptions in your check_ip function without telling you (except: pass). You could have any number of issues causing exceptions to be raised in this function, and if an exception is raising in every call of the function then you will get no results from your script while also not getting any feedback to log/console on the nature of the failure.
For the purposes of debugging, you should modify your exception handling to explicitly handle any exceptions that you want to pass over, and allow other exceptions to raise unhandled so that you can determine what your error conditions are.
I've tried looking about for an answer but I can't seem to find one that answers my specific problem.
Perhaps I don't know how to articulate the problem correctly.
I think I've pinpointed what it is, but the thing is I just don't know how to fix it.
EDIT: I was trying to use two clients on one TCP Socket. Can't do that. I'll have to think of another way. Solved, I guess.
So what I've got is are
1: Two Clients
2: One Server
The objective is this:
Have the server distribute new usernames to all the clients as they connect.
This is what happens when I run the program:
Server: Define Host, and Port, initialize it. Check
Client 1: Connects to the server. Check
Client 1: Once connected, sends a string to the server. Check
Server: Receives a string, checks if the string is in a list is created. If it is: Pass, if it's not, send to everyone the new string. Check
Client 1: [Now waiting to receive data] Recieves data, checks if the string received matches the one it sent. If it does, print("It's one of ours!"), else, make the new string = to Client 2 Username. Check
Client 2: Connects to server: Check
Server: [If it receives a string, prints it.] (Works) Checks if the new string is in the list. [It isn't] So It sends the new username to everyone, and then prints ("Sent to everyone") Check
But, when client 2 receives the string, it prints it. However, client 1 never recives the string.
And when running client one in IDLE, I noticed something went wrong as Client 1 tried to receive the data. (The while loop that the data = s.recv began looping real fast, instead of waiting)
I've asked around in chat, but it seems nobody's around right now. I've tried looking this up but I really can't find an answer. What I suspect is happening is that when my server sends to 'connection' the second time, it somehow overrides the original client connection.
Here's my server code:
from socket import *
import threading
import os
import csv
Username_List = []
host = input("Host: ")
port = input("Port: ")
ss = socket(AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
ss.listen(2)
while True:
try:
connection,address = ss.accept()
data = connection.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data in Username_List:
pass
else:
Username_List.append(translated_data)
connection.sendall(translated_data.encode())
print("Sent new username to everyone")
except IOError:
connection.close()
print("An exception with a connected user occured")
break
And here is my client code: [The only difference between client 1 and 2 is I changed the username variable]
# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv
Username = ("Owatch")
host = input("Host: ")
port = input("Port: ")
try:
ss = socket(AF_INET,SOCK_STREAM)
ss.connect((host,int(port)))
except IOError:
print("Aw no man")
ss.send(Username.encode())
while True:
try:
print("Waiting to Recieve Data")
data = ss.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data == Username:
print("It's one of ours!")
else:
Client_Username = translated_data
print (Client_Username)
except Exception as e:
print (vars(e))
If you could please help I'd be grateful.
If you know of an answer to my question that's already been asked, please tell me and I'll remove this post to avoid breaking rules. Thanks!
Right then I started with what you had then changed it till it worked what I've done is created a client class which starts a thread with each connection and adds it to a list of threads (please if I'm doing something horribly wrong smarter people correct me), the thread runs gets some data checks if that's in the list of user names if its not sends out a message to all the clients in the thread list with that name then the thread just chills out. Anyway on to the code.
SERVER!!!
import csv
class client(threading.Thread):
Username_List = []
def __init__(self, conn):
super(client, self).__init__()
self.conn = conn
def run(self):
print "Client thread started"
data = self.conn.recv(1024)
print "Received: {0}".format(data)
if data in client.Username_List:
self.send_msg("Welcome Back!")
else:
for cnt in threadz:
cnt.send_msg(data)
print("Sent new username to everyone")
client.Username_List.append(data)
while True:
# dont need nothing now
pass
def send_msg(self,msg):
self.conn.send(msg)
host = input("Host: ")
port = input("Port: ")
ss = socket() #AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
print "Server Opening on port: {0}".format(port)
ss.listen(2)
threadz = []
print "Begining Wait for connections"
while True:
try:
connection, address = ss.accept()
print "Got ONE!"
c = client(connection)
print "Recevied connection from:{0} On port:{1}".format(address[0],address[1])
c.start()
threadz.append(c)
print "Client appended to threadz, currently {0} threadz active".format(len(threadz))
except IOError,KeyboardInterrupt:
connection.close()
print("An exception with a connected user occured")
break
The CLIENT:
# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv
Username = ("ShyGuy")
host = input("Host: ")
port = input("Port: ")
try:
ss = socket() #AF_INET,SOCK_STREAM)
ss.connect((host,int(port))) #I was using ("localhost",1234) for testing
ss.send(Username)
except IOError:
print("Aw no man")
print("Waiting to Recieve Data")
while True:
try:
data = ss.recv(1024)
if data:
translated_data = data.decode()
print(translated_data)
if translated_data == Username:
print"Name: {0} has been registered on server!".format(translated_data)
else:
Client_Username = translated_data
print "New client name received: {0}".format(Client_Username)
except Exception as e:
print (vars(e))
That works on python 2.7 with two clients locally. Needs to use a semaphore to stop the threads printing at the same time as the main server loop prints: http://en.wikipedia.org/wiki/Semaphore_(programming)
This code does nothing graceful with client disconnects, but once you can work with the exceptions that a raised when that happens I'm sure you'll learn some more.
i tried to do client and server and look what i do
#Server
import socket
Host=''
Port=305
OK=socket.socket()
OK.bind((Host,Port))
OK.listn(1)
OK.accept()
and another one for client
#Client
impot socket
Host='192.168.1.4'
Port=305
OK=socket.socket()
OK.connect((Host,Port))
First thing : for now every thing is ok but i want when client connect to server :
server print "Hello Admin" in client screen
second thing : i want make like input command ! like
COM=raw_input('enter you command system:')
then client enter dir for example then server print the result in client screen
Look here, this is a simple echo server written in Python.
http://ilab.cs.byu.edu/python/socket/echoserver.html
When you create a connection, the story isn't over. Now it's time to send data over the connection. Create a simple "protocol" (*) and use it to transfer data from client to server and/or back. One simple example is a textual protocol of commands separated by newlines - this is similar to what HTTP does.
(*) Protocol: an agreement between two parties on the format of their communication.
I think you might want to do something like this:
client, addr = OK.accept()
client.send("Hello Admin")
And then use
data = client.recv(1024)
to get data from the client.
If you want to get command input from the client, you just need to execute the commands the client sends and send the output back back to the client.
from commands import getoutput
client.send(getoutput(client.recv(1024)))
Thats about the easiest solution possible.
For Client:
import os
import sys
impot socket
Host=raw_input ("Please enter ip : ")
Port=raw_input ("please Enter port :")
OK=socket.socket()
OK.connect((Host,Port))
print " Enter Command")
cmd = raw_input()
os.system(cmd)
I think that your codes has an issue:
you seem to have OK = socket.socket(), but I think it should be:
OK = socket.socket(socket.AF_INET, socket.STREAM), which would help if your making a connection. And your server has a problem: OK.listn(1) should be OK.listen(1). And, don't forget about send() and recv().
#Client
import socket
Host='192.168.1.4'
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.connect((Host,Port))
while True:
com = raw_input("Enter your command: ")
OK.send(com)
data = OK.recv(5000) #Change the buffer if you need to, I have it setup to run 5000
print "Received:\n" + data
which should work for the client
#Server
import socket
import os
Host=''
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.bind((Host,Port))
OK.listen(1)
conn, addr = OK.accept()
while True:
data = conn.recv(2048) #Change the buffer if needed
if data == "":
break
r = os.system(data)
conn.send(str(r)) #Note this will send 0 or 1, 0 = ran, 1 = error
Note: These fixes would work for Windows, I don't know about Unix systems.*