python multithreaded ssh app - python

I have an app I've scraped together to try and spawn 3 threads and ssh into a server simultaneously.
I wrote an obviously offensively coded application which I know is wrong which I am looking for some guidance for, to accomplish my initial end goal as mentioned above.
For the argument passing, I know I need to finesse it with something like cmd or cmd2 later on but for now that's not my primary concern.
I know that right now I'm spawning a subprocess and doing things serially. I look forward to your replies.
#!/usr/bin/python
import sys, os
import subprocess
if (len(sys.argv) > 1):
if( sys.argv[1] == 'start' ):
print "starting jboss"
arg = str(sys.argv[1])
elif( sys.argv[1] == 'stop' ):
print "stopping"
elif( sys.argv[1] == 'status' ):
print "getting status"
arg = str(sys.argv[1])
print arg
else:
print "start or stop?"
exit(1)
else:
print "unexpected error"
host = "10.24.14.10 "
command = "sudo /etc/init.d/jbossas " + arg
fullcommand = "ssh " + " " + host + " " + " " + command + " "+ arg
print "full command: ", fullcommand
process = subprocess.Popen(fullcommand, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output
host = "10.24.14.20 "
fullcommand = "ssh " + " " + host + " " + " " + command + " "+ arg
process = subprocess.Popen(fullcommand, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output
host = "10.30.1.1 "
fullcommand = "ssh " + " " + host + " " + " " + command + " "+ arg
process = subprocess.Popen(fullcommand, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output

Related

Difficulties in pipes between Python subprocesses in Linux

The following script (which should take the output from p1 and pipe it to p2, and then output the result in the terminal) doesn't seem to work as expected.
Code as follows :
#!/binr/bin/python
# Script to lauch mosquitto_sub to monitor a mqtt topic -- SYNTAX : mosk topic
import sys
import subprocess
total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
path = str(sys.argv[1])
print (path)
p1 = subprocess.Popen(['mosquitto_sub','-h','192.168.1.100','-t',path,'-v'], shell=False, stdout=subprocess.PIPE)
p2 = subprocess.Popen(['ts'], stdin=p1.stdout, shell=False, stdout=subprocess.PIPE)
for line in p2.stdout:
sys.stdout.write(line)
with an input as follows "./mosk2.py test/+" and whilst publishing MQTT via mosquitto on the relevant topics, I never get the expected output in the terminal
Solved - I ended up stepping neatly around the problem (cheating) as follows :
cmd = "mosquitto_sub -h 192.168.1.100 -v -t " + topic + " | ts"
print "The command which was executed is : " , cmd
def run_command(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print output.strip()
rc = process.poll()
return rc
run_command(cmd) #This is the lauch of the actual command

RPi 3 Python Script - NameError: name 'BluetoothSocket' is not defined

So I am relatively new to python scripting and I came across this code that is supposed to configure wifi over bluetooth between a raspberry pi and smart device. Unfortunately, I keep running into the error listed in the title. I was hoping someone can copy and run the code and enlighten me why i keep running into this error. All help is greatly appreciated!
#!/usr/bin/env python
import os
from bluetooth import *
from wifi import Cell, Scheme
import subprocess
import time
wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "
def wifi_connect(ssid, psk):
# write wifi config to file
f = open('wifi.conf', 'w')
f.write('country=GB\n')
f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
f.write('update_config=1\n')
f.write('\n')
f.write('network={\n')
f.write(' ssid="' + ssid + '"\n')
f.write(' psk="' + psk + '"\n')
f.write('}\n')
f.close()
cmd = 'mv wifi.conf ' + wpa_supplicant_conf
cmd_result = ""
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
# restart wifi adapter
cmd = sudo_mode + 'ifdown wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(2)
cmd = sudo_mode + 'ifup wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(10)
cmd = 'iwconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
cmd = 'ifconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
p = subprocess.Popen(['ifconfig', 'wlan0'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
ip_address = "<Not Set>"
for l in out.split('\n'):
if l.strip().startswith("inet addr:"):
ip_address = l.strip().split(' ')[1].split(':')[1]
return ip_address
def ssid_discovered():
Cells = Cell.all('wlan0')
wifi_info = 'Found ssid : \n'
for current in range(len(Cells)):
wifi_info += Cells[current].ssid + "\n"
wifi_info+="!"
print wifi_info
return wifi_info
def handle_client(client_sock) :
# get ssid
client_sock.send(ssid_discovered())
print "Waiting for SSID..."
ssid = client_sock.recv(1024)
if ssid == '' :
return
print "ssid received"
print ssid
# get psk
client_sock.send("waiting-psk!")
print "Waiting for PSK..."
psk = client_sock.recv(1024)
if psk == '' :
return
print "psk received"
print psk
ip_address = wifi_connect(ssid, psk)
print "ip address: " + ip_address
client_sock.send("ip-addres:" + ip_address + "!")
return
try:
while True:
server_sock=BluetoothSocket( RFCOMM )
server_sock,bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"
advertise_service( server_sock, "RaspberryPiServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
handle_client(client_sock)
client_sock.close()
server_sock.close()
# finished config
print 'Finished configuration\n'
except (KeyboardInterrupt, SystemExit):
print '\nExiting\n'
This code outputs
Traceback (most recent call last): File "test.py", line 128, in <module>
server_sock=BluetoothSocket( RFCOMM )
NameError: name 'BluetoothSocket' is not defined
Can you show us your python version ?
Just type:
$ python --version
bluetooth lib seems to be present. But not BluetoothSocket: try to install bluez and python-bluez
$ sudo apt-get install bluez
$ sudo apt-get install python-bluez

Need to start tomcat automatically

I am trying to develop this program which is used to start tomcat server version 7 using python. I am using ubuntu OS.
#!/usr/bin/python
import os
import subprocess
proc=raw_input("Enter the mode :")
os.environ["JAVA_HOME"] = '/usr/lib/jvm/java-7-openjdk-amd64/bin';
os.environ["JRE_HOME"]='/usr/lib/jvm/java-7-openjdk-amd64/jre';
os.environ["CATALINA_HOME"] = '/export/apps/tomcat7';
os.environ["PATH"] = '$JAVA_HOME/bin:$PATH';
if proc == "start":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'start'])
elif proc == "stop":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'stop'])
print "Tomcat stopped successfully"
elif proc == "restart":
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'stop'])
subprocess.call(['/export/apps/tomcat7/bin/catalina.sh', 'start'])
print "tomcat restarted successfully"
else:
print "error: give any mode"
print "Thank you"
But i keep getting this error.
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: uname: not found
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: dirname: not found
/export/apps/tomcat7/bin/catalina.sh: 1: /export/apps/tomcat7/bin/catalina.sh: tty: not found
/export/apps/tomcat7/bin/catalina.sh: 379: /export/apps/tomcat7/bin/catalina.sh: touch: not found
Anyone please help me to rectify this error..
Finally i got the solution to develop a python script used to start tomcat server automatically. Herewith i have submitted my code..
#!/usr/bin/python
import os
import subprocess
proc=raw_input("Enter the mode :")
os.environ["JAVA_HOME"] = '/usr/lib/jvm/java-7-openjdk-amd64'
os.environ["CATALINA_HOME"] = '/export/apps/tomcat7'
if proc == "start":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh start',shell=True)
print "Tomcat started successfully"
elif proc == "stop":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh stop',shell=True)
print "Tomcat stopped successfully"
elif proc == "restart":
os.getcwd()
os.chdir("/export/apps/tomcat7/bin/")
os.getcwd()
subprocess.call('sh catalina.sh stop',shell=True)
subprocess.call('sh catalina.sh start',shell=True)
print "tomcat restarted successfully"
else:
print "error: give any mode"
print "Thank you"
The python script to start, stop, check status & restart tomcat. That works for Python 2.6
#!/usr/bin/env python
# This is an init script to start, stop, check status & restart tomcat.
import sys
import subprocess
import time
scriptName = 'tomact_init.py'
tomcatBinDir = '/apps/apache-tomcat-7.0.63/bin'
tomcatShutdownPeriod = 5
commandToCheckTomcatProcess = "ps -ef | grep -v grep | grep " + tomcatBinDir + " | wc -l"
commandToFindTomcatProcessId = 'ps -ef | grep -v grep | grep ' + tomcatBinDir + ' | awk \'{print $2}\''
def isProcessRunning():
pStatus = True
tProcess = subprocess.Popen(commandToCheckTomcatProcess, stdout=subprocess.PIPE, shell=True)
out, err = tProcess.communicate()
if int(out) < 1:
pStatus = False
return pStatus
def usage():
print "Usage: python " + scriptName + " start|stop|status|restart"
print "or"
print "Usage: <path>/" + scriptName + " start|stop|status|restart"
def start():
if isProcessRunning():
print "Tomcat process is already running"
else:
print "Starting the tomcat"
subprocess.Popen([tomcatBinDir + "/startup.sh"], stdout=subprocess.PIPE)
def stop():
if isProcessRunning():
print "Stopping the tomcat"
subprocess.Popen([tomcatBinDir + "/shutdown.sh"], stdout=subprocess.PIPE)
time.sleep(tomcatShutdownPeriod)
if isProcessRunning():
tPid = subprocess.Popen([commandToFindTomcatProcessId], stdout=subprocess.PIPE, shell=True)
out, err = tPid.communicate()
subprocess.Popen(["kill -9 " + out], stdout=subprocess.PIPE, shell=True)
print "Tomcat failed to shutdown, so killed with PID " + out
else:
print "Tomcat process is not running"
def status():
if isProcessRunning():
tPid = subprocess.Popen([commandToFindTomcatProcessId], stdout=subprocess.PIPE, shell=True)
out, err = tPid.communicate()
print "Tomcat process is running with PID " + out
else:
print "Tomcat process is not running"
if len(sys.argv) != 2:
print "Missing argument"
usage()
sys.exit(0)
else:
action = sys.argv[1]
if action == 'start':
start()
elif action == 'stop':
stop()
elif action == 'status':
status()
elif action == 'restart':
stop()
start()
else:
print "Invalid argument"
usage()
Python does not perform variable substitution as shell does, so you're passing a wrong PATH. You should try with
os.environ["PATH"] = '/usr/lib/jvm/java-7-openjdk-amd64/bin:%s' % os.environ["PATH"]

Can't quit while running long Popen command

I am running the below code which runs a command line application which runs for about 40 mins. While this is running my QUIT button is not accessible so I am unable to quit the running application. The below code and the button are both seated in their own def. Any ideas as to how I can get a working quit button while my application is running?
command1 = transporterLink + " -m verify -f " + indir1 + " -u " + username + " -p " + password + " -o " + logPath + " -s " + provider1 + " -v eXtreme"
master, slave = pty.openpty()
process = Popen(command1, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)
stdout = os.fdopen(master)
global subject
subject = "Test"
while True:
wx.Yield()
line = stdout.readline()
line = line.rstrip()
print line
if "Returning 1" in line:
result1 = "Verify FAILED!"
subject = "FAILED! - "
self.sendEmail(self)
break
if "Returning 0" in line:
result1 = "Verify PASSED!"
subject = "PASSED! - "
self.sendEmail(self)
break
stdout.readline is blocking until there is something in stdout. You could use select module's poll
command1 = transporterLink + " -m verify -f " + indir1 + " -u " + username + " -p " + password + " -o " + logPath + " -s " + provider1 + " -v eXtreme"
master, slave = pty.openpty()
process = Popen(command1, shell=True, stdin=PIPE, stdout=master, stderr=slave, close_fds=True)
stdout = os.fdopen(master)
import select
q = select.poll()
q.register(stdout,select.POLLIN)
global subject
subject = "Test"
while True:
wx.Yield()
events = q.poll(0)
for fd, flags in events:
assert(fd == stdout.fileno())
line = stdout.readline()
print line
if "Returning 1" in line:
result1 = "Verify FAILED!"
subject = "FAILED! - "
self.sendEmail(self)
sys.exit(0)
if "Returning 0" in line:
result1 = "Verify PASSED!"
subject = "PASSED! - "
self.sendEmail(self)
sys.exit(0)

Stuck in while True loop python

I am stuck in a while True loop which I can't seem to break, any suggestions please:
command1 = transporterLink + " -m verify -f " + indir1 + " -u " + username + " -p " + password + " -o " + indir1 + "/VerifyLog.txt -s " + provider1 + " -v eXtreme"
master, slave = pty.openpty()
process = Popen(command1, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)
stdout = os.fdopen(master)
while True:
wx.Yield()
line = stdout.readline()
print line.rstrip()
if not line:
break
process.wait()
The simplest explanation is that you never get an empty line from stdout. Note that print line.rstrip() does not modify line; for example, if the last line ended with a newline, the loop would continue.
Sorted. I know that at the end of the last line it will return one of two strings so just needed to search for either of these two:
process = Popen(command1, shell=True, stdin=PIPE, stdout=slave, stderr=slave, close_fds=True)
stdout = os.fdopen(master)
while True:
wx.Yield()
line = stdout.readline()
line = line.rstrip()
print line
if "Returning 1" in line:
break
if "Returning 0" in line:
break

Categories