How to catch the ffmpeg connection error on python - python

I am working on the ffmpeg with python.This works when the remote server is working well, however when the remote server is down, I could see the message on the shell saying
'Connection to tcp://xxxxxxx failed: Connection refused, blabla'
pro = sp.Popen(command, preexec_fn=os.setsid, shell=False, stderr=sp.PIPE, stdout=sp.PIPE)
catch exception approach 1:
try:
out = self.pro.stderr.readline()
while out:
print '......'
except BrokenPipeError:
print 'err'
catch exception approach 2:
for line in self.pro.stderr:
try:
print line
except BrokenPipeError:
print 'error'
However none of these works.

communicate() returns a tuple (stdoutdata, stderrdata) so you just need to print the second element:
cmd = ('ffmpeg', '-hide_banner', '-i', 'tcp://127.0.0.1:10000', '-c', 'copy', '-f', 'null', '/dev/null');
s = subprocess.Popen(cmd, shell=False, preexec_fn=os.setsid, stderr=subprocess.PIPE)
# print stderr
print s.communicate()[1]
Output:
$ ./test.py
[tcp # 0x55a01c945000] Connection to tcp://127.0.0.1:10000 failed: Connection refused
tcp://127.0.0.1:10000: Connection refused

Related

How do i suppress terminal output on ping, but still be able to validate response?

So I've been struggling to suppress my terminal output whenever I send a packet. I just want to validate the response (0,2 or else) so my terminal won't get spammed with the standard "ping statistics, packets received, packet loss". How would I go about doing this code-wise? I'm not looking for a terminal / bash "way".
def ping():
hosts = open('hosts.txt', 'r')
for host_ip in hosts:
res = subprocess.call(['ping', '-c', '1', host_ip])
if res == 0:
print "ping to", host_ip, "OK"
elif res == 2:
print "no response from", host_ip
else:
print "ping to", host_ip, "failed!"
I just pinged to google dns servers using python's subprocess.Popen class and it returns nothing to the terminal except the returncode I printed in code
import subprocess
process = subprocess.Popen(['ping','-c' ,'1', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
returncode = process.returncode
print(returncode)
OUTPUT
0

subprocess.CalledProcessError: returned non-zero exit status 1 for non-pingable destination

I am writing a python script to calculate packet loss through ping an IP address using subprocess module in linux. More than one IP address kept in CSV file. It is running fine when the pingable destination are only given.
But throwing an error when the non-pingable IP given in the CSV file and then the script is exiting without checking the other IP address in that CSV file. So I am not able to capture the packet loss for the non-pingable destination which is the main purpose the script.
Please suggest a way forward.
subprocess.check_output(['ping','-c 4',hostname], shell=False,
universal_newlines=True).splitlines()
subprocess.CalledProcessError: Command '['ping', '-c 4', '192.168.134.100']' returned non-zero exit status 1
It is just that subprocess returns an error if your ping has 100% packet loss, destination unreachable or any other problem. What you could do is:
try:
# subprocess code here
except:
# some code here if the destination is not pingable, e.g. print("Destination unreachable..") or something else
pass # You need pass so the script will continue on even after the error
Try this Code:
import subprocess
def systemCommand(Command):
Output = ""
Error = ""
try:
Output = subprocess.check_output(Command,stderr = subprocess.STDOUT,shell='True')
except subprocess.CalledProcessError as e:
#Invalid command raises this exception
Error = e.output
if Output:
Stdout = Output.split("\n")
else:
Stdout = []
if Error:
Stderr = Error.split("\n")
else:
Stderr = []
return (Stdout,Stderr)
#in main
Host = "ip to ping"
NoOfPackets = 2
Timeout = 5000 #in milliseconds
#Command for windows
Command = 'ping -n {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
#Command for linux
#Command = 'ping -c {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
Stdout,Stderr = systemCommand(Command)
if Stdout:
print("Host [{}] is reachable.".format(Host))
else:
print("Host [{}] is unreachable.".format(Host))

Detecting internet for a specific interface over Python

I'm looking for a solution to check whether or not a specific interface (eth0, wlan0, etc) has internet or not.
My situation is as follows; I have 2 active connections. One ethernet connection that has no internet (eth0) and one Wireless connection (wlan0) that has internet. Both have recieved an LAN IP from their respective DHCP servers.
I have come to the conclusion, but I am very open to suggestions, that the best solution would:
Have a ping command:
ping -I wlan0 -c 3 www.google.com
And have Python pick up or not I am able to reach the destination (check for: "Destination Host Unreachable")
import subprocess
command = ["ping", "-I", "wlan0", "-c", "3", "www.google.com"]
find = "Destination Host Unreachable"
p = subprocess.Popen(command, stdout=subprocess.PIPE)
text = p.stdout.read()
retcode = p.wait()
if find in command:
print "text found"
else:
print "not found"
This however does not yield the best result, and I could really use some help.
Thanks!
The text variable prints out the pint command output, it's just the finding the text inside the print command output that's not working.
Yes because you don't capture stderr, you can redirect stderr to stdout, you can also just call communicate to wait for the process to finish and get the output:
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out,_ = p.communicate()
You can also just use check_call which will raise an error for any non-zero exit status:
from subprocess import check_call, CalledProcessError, PIPE
def is_reachable(inter, i, add):
command = ["ping", "-I", inter, "-c", i, add]
try:
check_call(command, stdout=PIPE)
return True
except CalledProcessError as e:
print e.message
return False
If you want to only catch a certain error, you can check the return code.
def is_reachable(inter, i, add):
command = ["ping", "-I", inter, "-c", i, add]
try:
check_call(command, stdout=PIPE)
return True
except CalledProcessError as e:
if e.returncode == 1:
return False
raise

Python script for SSH through PuTTY

I am able to give the following command in the command-line
C:\>cd "C:\Program Files\ExtraPuTTY\Bin"
C:\Program Files\ExtraPuTTY\Bin>putty.exe -ssh root#172.20.0.102 22
This helps me open the SSH session through PuTTY.
Whereas I am not able to reproduce them in the Python script.
cwd="C://Program Files//ExtraPuTTY//Bin"
COMMAND="ls"
ssh = Popen(['putty.exe -ssh','%s'%HOST, COMMAND,cwd],shell=True,stdout=f,stderr=f)
The error that I see is
"putty.exe -ssh"' is not recognized as an internal or external command,operable program or batch file
In the putty download page, download and install plink, and make sure its in the windows path ($PATH variable)
Then, this python snippet should work:
import subprocess
cmd='plink -ssh {}#{} -pw {}'.format(user,server,password)
sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
sp.stdin.write(stdin)
sp.stdin.close()
stdout= sp.stdout.read()
stderr=sp.stderr.read()
sp.wait()
stdin is the commands typed by the user in the terminal, stdout and stderr are the server output.
Fill in your credentials in the user="root", server="172.20.0.102 22" and maybe password for the ssh connection
You have to pass the cwd as the cwd parameter of the Popen:
Popen(['putty.exe -ssh'...], shell=True, stdout=f, stderr=f, cwd=cwd)
And you should use Plink, not PuTTY, for automating the remote command execution. The Plink accepts the command on its command-line (PuTTY does not):
Popen(['plink.exe -ssh root#172.20.0.102 ls'], shell=True, stdout=f, stderr=f, cwd=cwd)
Even better, use a native Python SSH library, like Paramiko:
Python Paramiko - Run command
I know it' a bit beside the question, but that the most closed topic I found (I'd like to found that code a week ago on that post)
I was looking for a code to massively check if a password is active, and change it if possible
Putty have several cli tool like plink and pscp whch are useful for a lot of stuff.
Here is python 3 function to connect to a ssh server and accept ssh key.
using pscp allow a auto accept key... can be useful for first time
def TestSSHConnection(IP_Addr,User,Password,verbosity=0, force_plink=False):
#Some infos about returned code
# 0 = Error Or crash
# 1 = Connection ok
# 2 = No connect Password Error
# 3 = SSH key trouble (shit append)
# 4 = Timeout
# 5 = Host Unreachable
# 6 = Connection Crash
out=""
err=""
try:
if force_plink:
print("echo y | plink -l "+str(User)+" -pw "+str(Password)+" -batch "+str(IP_Addr)+" exit",)
ssh=subprocess.Popen("echo y | plink -l "+str(User)+" -pw "+str(Password)+" -batch "+str(IP_Addr)+" exit",shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,encoding='utf8')#,stdin=subprocess.PIPE)
else:
print("echo y | pscp -l "+str(User)+" -pw "+str(Password)+" -ls "+str(IP_Addr)+":/",)
ssh=subprocess.Popen("echo y | pscp -l "+str(User)+" -pw "+str(Password)+" -ls "+str(IP_Addr)+":/",shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = ssh.communicate()
try:
out = out.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
if verbosity>1:
print("While decoding stdout: "+str(type(inst)))
try:
err = err.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
print("While decoding stderr: "+str(type(inst)))
ssh.kill()
del ssh
except Exception as inst:
print("Crash"+str(inst))
return 0
if len(err)>0:
if 'Unable to open connection' in err or 'Host does not exist' in err:
if verbosity>0: print("Unreachable")
result = 5
if verbosity>1:
print()
print("-"*30)
print(err)
print("-"*30)
elif 'Connection timed out' in err:
result = 4
elif 'The server\'s host key is not cached in the registry' in err:
result = 3
if verbosity>1:
print()
print("SSH key Err".center(30,"-"))
print(err)
print("-"*30)
elif 'Access denied' in err:
result = 2
if verbosity>2:
print()
print("Denied".center(30,"-"))
print(err)
print("-"*30)
else:
result = 6
if verbosity>0: print("ConnCrash")
print("Oups".center(30,"-"))
print(err)
print("-"*30)
else:
if verbosity>0: print("Conn ok")
result = 1
del out,err
return result
Of cource, this juste Check connection (and accept ssh key)
So here is a code to run a script on the host (precisely a password change).
To do so, you can't use one line syntax (even it must work, it won't, i tried) You have to pass through a script file and push it with plink.
def ChangeMyPassword(IP_Addr,User,Old_Password,New_Password,verbosity=0):
#Some infos about returned code
# 0 = Error Or crash
# 1 = Change Ok
# 2 = Old Password Error
# 3 = SSH key trouble (shit append)
# 4 = Timeout
# 5 = Host Unreachable
# 6 = Connection Crash
out=""
err=""
try:
path_script = "."+os.sep+"Script_chmdp_"+str(IP_Addr)+".sh"
if os.path.exists(path_script):os.remove(path_script)
fic_script = codecs.open(path_script,'w', encoding='utf8')
fic_script.write('echo -e \"'+str(Old_Password)+'\\n'+str(New_Password)+'\\n'+str(New_Password)+'\" | passwd')
fic_script.flush()
fic_script.close()
cmd = "plink -l "+str(User)+" -pw "+str(Old_Password)+" -batch "+str(IP_Addr)+ " "
cmd += "-m "+path_script
print(str(cmd))
ssh=subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,encoding='utf8')#,stdin=subprocess.PIPE)
out,err = ssh.communicate()
try:
out = out.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
if verbosity>1:
print("While decoding stdout: "+str(type(inst)))
try:
err = err.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
print("While decoding stderr: "+str(type(inst)))
ssh.kill()
del ssh
except Exception as inst:
print("Crash"+str(inst))
return 0
if 'all authentication tokens updated successfully' in out:
if verbosity>0: print("Conn ok")
result = 1
else:
if verbosity>0: print("Something goes wrong, hope we do not crash your server :)")
result = 0
del out,err
return result
So now you have two function to massively change password on your systems.
Bonus: a function to get /etc/passwd and /etc/shadow. Why? for educationnal use on your IT admin like 'hey you f*** up and use the same password everywhere, and now all this account can be Bruteforced. So clean up your mess
def GetPass(IP_Addr,User,Password,verbosity=0, force_plink=False):
#Some infos about returned code
# 0 = Error Or crash
# 1 = Connection ok
# 2 = No connect Password Error
# 3 = SSH key trouble (shit append)
# 4 = Timeout
# 5 = Host Unreachable
# 6 = Connection Crash
out=""
err=""
try:
ssh=subprocess.Popen("echo "+str(Password)+" | plink -l "+str(User)+" -pw "+str(Password)+" -batch "+str(IP_Addr)+" sudo cat /etc/passwd;sudo cat /etc/shadow",shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,encoding='utf8')#,stdin=subprocess.PIPE)
out,err = ssh.communicate()
try:
out = out.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
if verbosity>1:
print("While decoding stdout: "+str(type(inst)))
try:
err = err.decode('utf-8')
except AttributeError as inst:
pass
except Exception as inst:
print("While decoding stderr: "+str(type(inst)))
ssh.kill()
del ssh
except Exception as inst:
print("Crash"+str(inst))
return 0
if len(err)>0:
if 'Unable to open connection' in err or 'Host does not exist' in err:
if verbosity>0: print("Unreachable")
result = 5
if verbosity>1:
print()
print("-"*30)
print(err)
print("-"*30)
elif 'Connection timed out' in err:
result = 4
elif 'The server\'s host key is not cached in the registry' in err:
result = 3
if verbosity>1:
print()
print("SSH key Err".center(30,"-"))
print(err)
print("-"*30)
elif 'Access denied' in err:
result = 2
if verbosity>2:
print()
print("Denied".center(30,"-"))
print(err)
print("-"*30)
else:
result = 6
if verbosity>0: print("ConnCrash")
print("Oups".center(30,"-"))
print(err)
print("-"*30)
else:
if verbosity>0: print("Conn ok")
result = out
del out,err
return result
Some more notes:
if you don't use shell=True, you don't get the output, and it does not work, I don't know why.
I also tried a asynchronous communication to send comand line by line, it does not work.
I also tried the ssh command (yes it now exist on windows \o/) but it does not work for my purpose.
Hope this help someone one day, it would have helped me a lot a week ago :)

Get output of system ping without printing to the console

I want to call ping from Python and get the output. I tried the following:
response = os.system("ping "+ "- c")
However, this prints to the console, which I don't want.
PING 10.10.0.100 (10.10.0.100) 56(86) bytes of data.
64 bytes from 10.10.0.100: icmp_seq=1 ttl=63 time=0.713 ms
64 bytes from 10.10.0.100: icmp_seq=2 ttl=63 time=1.15 ms
Is there a way to not print to the console and just get the result?
To get the output of a command, use subprocess.check_output. It raises an error if the command fails, so surround it in a try block.
import subprocess
try:
response = subprocess.check_output(
['ping', '-c', '3', '10.10.0.100'],
stderr=subprocess.STDOUT, # get all output
universal_newlines=True # return string not bytes
)
except subprocess.CalledProcessError:
response = None
To use ping to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call will raise and error if the return value is not 0. To suppress output, redirect stdout and stderr. With Python 3 you can use subprocess.DEVNULL rather than opening the null file in a block.
import os
import subprocess
with open(os.devnull, 'w') as DEVNULL:
try:
subprocess.check_call(
['ping', '-c', '3', '10.10.0.100'],
stdout=DEVNULL, # suppress output
stderr=DEVNULL
)
is_up = True
except subprocess.CalledProcessError:
is_up = False
In general, use subprocess calls, which, as the docs describe, are intended to replace os.system.
If you only need to check if the ping was successful, look at the status code; ping returns 2 for a failed ping, 0 for a success.
I'd use subprocess.Popen() (and not subprocess.check_call() as that raises an exception when ping reports the host is down, complicating handling). Redirect stdout to a pipe so you can read it from Python:
ipaddress = '198.252.206.140' # guess who
proc = subprocess.Popen(
['ping', '-c', '3', ipaddress],
stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode == 0:
print('{} is UP'.format(ipaddress))
print('ping output:')
print(stdout.decode('ASCII'))
You can switch to subprocess.DEVNULL* if you want to ignore the output; use proc.wait() to wait for ping to exit; you can add -q to have ping do less work, as it'll produce less output with that switch:
proc = subprocess.Popen(
['ping', '-q', '-c', '3', ipaddress],
stdout=subprocess.DEVNULL)
proc.wait()
if proc.returncode == 0:
print('{} is UP'.format(ipaddress))
In both cases, proc.returncode can tell you more about why the ping failed, depending on your ping implementation. See man ping for details. On OS X the manpage states:
EXIT STATUS
The ping utility exits with one of the following values:
0 At least one response was heard from the specified host.
2 The transmission was successful but no responses were received.
any other value
An error occurred. These values are defined in <sysexits.h>.
and man sysexits lists further error codes.
The latter form (ignoring the output) can be simplified by using subprocess.call(), which combines the proc.wait() with a proc.returncode return:
status = subprocess.call(
['ping', '-q', '-c', '3', ipaddress],
stdout=subprocess.DEVNULL)
if status == 0:
print('{} is UP'.format(ipaddress))
* subprocess.DEVNULL is new in Python 3.3; use open(os.devnull, 'wb') in it's place in older Python versions, making use of the os.devnull value, e.g.:
status = subprocess.call(
['ping', '-q', '-c', '3', ipaddress],
stdout=open(os.devnull, 'wb'))

Categories

Resources