I'm attempting to use the re module to look through some terminal output. When I ping a server through terminal using ping -n 1 host (I'm using Windows), it gives me much more information than I want. I want just the amount of time that it takes to get a reply from the server, which in this case is always denoted by an integer and then the letters 'ms'. The error I get explains that the output from the terminal is not a string, so I cannot use regular expressions on it.
from os import system as system_call
import re
def ping(host):
return system_call("ping -n 1 " + host) == 0
host = input("Select a host to ping: ")
regex = re.compile(r"\w\wms")
final_ping = regex.search(ping(host))
print(final_ping)
system returns 0, not anything too useful. However, if we were to do subprocess, we can get teh output, and store it to a variable, out, then we can regex search that.
import subprocess
import re
def ping(host):
ping = subprocess.Popen(["ping", "-n", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = ping.communicate()
return str(out)
host = input("Select a host to ping: ")
final_ping = re.findall("\d+ms",ping(host))[0]
print(final_ping)
Output:
22ms
There are two problems with your code:
Your ping function doesn't return the terminal output. It only returns a bool that reports if the ping succeeded. The ping output is directly forwarded to the terminal that runs the Python script.
Python 3 differentiates between strings (for text, consisting of Unicode codepoints) and bytes (for any data, consisting of bytes). As Python cannot know that ping only outputs ASCII text, you will get a bytes object if you don't specify which text encoding is in use.
It would be the best to use the subprocess module instead of os.system. This is also suggested by the Python documentation.
One possible way is to use subprocess.check_output with the encoding parameter to get a string instead of bytes:
from subprocess import check_output
import sys
def ping(host):
return check_output(
"ping -n 1 " + host,
shell=True,
encoding=sys.getdefaultencoding()
)
...
EDIT: The encoding parameter is only supported since Python 3.6. If you are using an older version, try this:
from subprocess import check_output
import sys
def ping(host):
return check_output(
"ping -n 1 " + host,
shell=True
).decode()
...
Related
My problem is after executing below code I am able to see outputs of each command in shell. How can I get that shell output to the file
I have tried with the below but it does not work
python pr.py >> pr.txt
import os
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
os.system("udstask expireimage -image" + i)
After executing "os.system("udstask expireimage -image" + i)" every time this will display status of the command to the file
You could try something like :
import os
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
os.system("udstask expireimage -image" + i + " > pr.txt")
It would redirect the output of the command to pr.txt.
You should use subprocess instead of os.system which has more efficient stream handling and gives you more control while calling a shell command:
import os
import subprocess
f=open("pr1.txt","r")
df=0
for i in f:
df=df+1
if df==4:
break
print i
task = subprocess.Popen(["udstask expireimage -image" + i],stdout=subprocess.PIPE,shell=True)
task_op = task.communicate()
task.wait()
Now you have your output stored in task_op which you can write onto a file or do whatever you wish to. It is in tuple form and you may need to write only required part.
I've been trying to make a script that can print the Ubuntu SSH key located in ~/.ssh/authorised_keys/
Basically I want the script to print out exactly what cat ~/.ssh/authorised_keys/ would output.
I have tried using subprocess.check_output but it always returns an error.
Thanks
What about this ?
import os
os.system('cat ~/.ssh/authorised_keys')
If you want to capture the output to a variable, use subprocess. If not, you can use os.system as user803422 has mentioned
import os, subprocess
path = '~/.ssh/authorized_keys'
cmd = 'cat ' + os.path.expanduser(path)
output = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
response = output.communicate()
print (response)
You can read the file directly in Python, there is not really a need to use subprocess:
import os
print(open(os.path.expanduser('~/.ssh/authorized_keys')).read())
I am trying to learn network scripting via Python. I am trying to extract device names from file "Device_List" and then ssh to the device, executing a command on it and printing the output.
It works fine when I use IP address in the file however it does not if I use a hostname. I tried this on an Ubuntu Trusty as well as Mac OSX.
I get the following error:
FWIP = socket.gethostbyname(name)
socket.gaierror: [Errno -2] Name or service not known
I am able to resolve the hostname on both machines so it is not a DNS issue.
Moreover, if I input the device name from keyboard instead of file, it works fine.
Could you please help me find the issue?
My Code:
import datetime
import paramiko
import socket
import time
import sys
import getpass
with open("Device_List") as dev:
for name in dev:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Uname = raw_input("Username : ")
Pw = getpass.getpass()
print "Connected to ", name
FWIP = socket.gethostbyname(name)
ssh.connect(FWIP, username=Uname,password=Pw)
remote_conn = ssh.invoke_shell()
remote_conn.send("set cli pager off\n")
sys.stdout.flush()
command = raw_input("Enter Command to run : ")
remote_conn.send(command + "\n")
time.sleep(2)
output = remote_conn.recv(65534)
print output
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print "Moving Onto Next Device..."
print "Device List Over"
When you iterate over lines in a text file, e.g. your
with open("Device_List") as dev:
for name in dev:
the default I/O subsystem always includes the '\n' line ending character. One reason is that this way you can tell when a text file ends without ending the final line.
Get used to using (e.g.) dev.rstrip() when you don't want that.
# -*- coding: utf-8 -*-
# coding: utf-8
import sys
import os
import time
b = 'sudo tshark -i eth0 -R “tcp contains “attack”” -T fields -e ip.src -a duration:60>output.txt'
a = os.popen(b)
time.sleep(32)
f = open('output.txt','r')
text = 'IP address of attacker is'
print (text), f.read()
f.close
I am trying to execute this code to capture packets using tshark but i am getting this error:
tshark: "�" was unexpected in this context.
Please help me why that error is caused, thank you
The error message is because tshark tries to disable some dangerous functions in Lua like dofile.
If you don't need Lua in tshark, you can disable Lua support: edit init.lua, change disable_lua = false to disable_lua = true.
If you need Lua support, read Platform-Specific information about capture privileges, see how to capture packets without root rivilege.
from subprocess import call
import sys
import os
import subprocess
if(call("hg clone --insecure https://mixmaster.netwitness.local/" + "sys.argv[1]", shell=True)):
sys.stdin = sys.argv[2]
sys.stdin = sys.argv[3]
else :
print("error")
Is there a reason why the argument is in quotes? Also use % to replace tokens in your string. Change it to this:
if(call("hg clone --insecure https://mixmaster.netwitness.local/%s" % sys.argv[1], shell=True)):
EDIT
If you want to pass all the arguments separated by spaces, use this
if(call("hg clone --insecure https://mixmaster.netwitness.local/%s" % (" ".join(sys.argv[1:])), shell=True)):
subprocess.call is more easily called with a list of parameters. That way you don't have to worry about spaces in the arguments that you want to give to hg. As you indicate in your comments on #Rajesh answer, that you want 3 arguments passed to hg, the following should work:
from subprocess import call
import sys
import os
import subprocess
cmd = ["hg", "clone", "--insecure", "https://mixmaster.netwitness.local/", sys.argv[1], sys.argv[2], sys.argv[3]]
if not (call(cmd, shell=True)):
print("error")
If you really want to provide sys.argv[2] and sys.argv[3] as the input to hg prompts. You should not use call as it can block the hg process, use Popen.