I have a Python 2.7 Script that uses fabric and it uses a hostfile that has 4 hosts on it. I am having issues with it exiting after the second function is ran. Once it hits the "except" in checkHostFile it quits and does not follow the main() and go to the installedChoice where it asks user for a raw_input. I also ran the script so that it does not hit the "except" in checkHostFile and just does "try" but it will then just hang after running on the last host. Anyone know how I could rewrite it so it continues and does not exit or hang after finishing the checkHostFile()??
I run the script by running python "filename" and it will run the main() function.
Note: I have tried running it also with "pass" in the "except" in checkHostFile function and it still exits.
from fabric.api import *
from getpass import getpass
import os
import sys
import tsmFunctions
import logging
import traceback
env.hosts = open('hosts_file', 'r').readlines()
env.roledefs = {
'localhost': ['localhost'],
}
with open("./original_hostlist") as f:
env.roledefs['installhosts'] = f.readlines()
def main():
print 67 * "-"
original_hostlist = raw_input('Do you want to proceed? [yes/no]: ')
print 67 * "-"
if original_hostlist == 'yes':
execute(removeFiles)
execute(checkHostFile)
installedChoice = raw_input('Is this a new install, uninstall or an upgrade? [install/uninstall/upgrade](or enter exit to quit): ')
start(installedChoice)
elif original_hostlist == 'no':
print "Goodbye!"
#roles('localhost')
def removeFiles():
with settings(warn_only=True):
with hide ('running','output','stderr','stdout','aborts','everything'):
local('rm host_file_bad')
local('rm hosts_file')
#roles('installhosts')
#task
#serial
def checkHostFile():
with settings(warn_only=True):
response = run('uname -r | grep -c \"el\"')
if response == '1':
f = open('hosts_file', 'a')
f.write(env.host + "\n")
f.close()
else:
f = open('host_file_bad', 'a')
f.write(sys.stderr + "\n")
f.close()
if __name__ == '__main__':
main()
Update: i have modified function checkHostFile() to use if and else: The script is going to the next function if it only hits the if in checkHostFile. But it is still failing if it goes to else (it goes to else if the host is unreachable and cannot do the fabric run command).
MacBook-Pro-2:$ python pythonfile.py
[localhost] Executing task 'removeFiles'
Fatal error: Name lookup failed for fake.apple.com
Underlying exception:
nodename nor servname provided, or not known
Aborting.
Related
I have a Linux box that runs Cisco IOS and need to SSH into it sometimes to reboot it. I've written a batch file that calls on Cygwin. Cygwin then calls on Python+PythonScript.
Batch File:
cd c:\cygwin64\bin
bash --login -i -c "python3 /home/Owner/uccxtesting.py"
Python Script
import pexpect
import time
import sys
server_ip = "10.0.81.104"
server_user = "administrator"
server_pass = "secretpassword"
sshuccx1 = pexpect.spawn('ssh %s#%s' % (server_user, server_ip))
sshuccx1.logfile_read = sys.stdout.buffer
sshuccx1.timeout = 180
sshuccx1.expect('.*password:')
sshuccx1.sendline(server_pass)
sshuccx1.expect('.admin:')
sshuccx1.sendline('utils system restart')
sshuccx1.expect('Enter (yes/no)?')
sshuccx1.sendline('yes')
time.sleep(30)
When I run this, it stops at Enter yes/no. This is what I'm getting:
I've seen plenty of examples of pexpect with expect, but there is some white space out beside the question mark. I just don't know how to tell python to expect it.
There may be a bug:
utils system restart prompts for force restart (https://bst.cisco.com/bugsearch/bug/CSCvw22828)
Replace time.sleep(30) with the following code to answer a possible force restart prompt. If it works, you can get rid of the try...except and print commands that I added for debugging:
try:
index = -1
while index != 0:
sshuccx1.expect_exact(['succeeded', 'force', ], timeout=300)
if index == 2:
print('Forcing restart...')
sshuccx1.sendline('yes')
print('Operation succeeded')
print(str(child.before))
except pexpect.ExceptionPexpect:
e_type, e_value, _ = sys.exc_info()
print('Error: ' + pexpect.ExceptionPexpect(e_type).get_trace())
print(e_type, e_value)
Also, change sshuccx1.expect('Enter (yes/no)?') to sshuccx1.expect_exact('Enter (yes/no)?'). The expect method tries to match a regex pattern, and it may get caught on the parentheses (see https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect_exact)
I wanted to use PowerShell command through Python so I got this function
Functions.py:
import subprocess as sp
def makeconnection():
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout= sp.PIPE)
if __name__ == "__main__":
makeconnection()
Main.py:
from Functions import makeconnection
#...Codes...
try:
appdatapath = os.getenv('appdata')
with open(appdatapath + r'\Microsoft\Network\Connections\Pbk\rasphone.pbk', "r+") as f:
if f.read().find('CookieVPN') != -1:
print("VPN Connection: OK")
else:
#1. This code doesn't work
makeconnection()
#2. Then if I replace the line above with this one it works
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout=sp.PIPE)
print("VPN Connection: Created")
except Exception as e:
print('\n\nSomething went wrong while accessing the connection\n' + '-' * 15)
print(e)
input('\n\n *** Press Enter To Exit ***')
sys.exit()
#...Rest of the Codes...
It
works fine on its own but if I import this into another .py file and call it from there it raises the "permission denied" error from PowerShell.
What causes this and how to fix it?
Hi have python program in which a start method is defined, in start method i am calling a win32serviceutil.StartService(service) method to start a service, like
import os, platform, subprocess
try:
import win32serviceutil
except:
os.system("pip install pywin32")
os.system("pip install pypiwin32")
import win32serviceutil
OS = platform.system() #will get you the platform/OS
print("You are using ", OS)
if __name__=='__main__':
service = 'WSearch'
def startByCLI():
cmd = 'net start '+service
os.system(cmd)
def startByPython():
# subprocess.check_output(["sc", "start", service], stderr=subprocess.STDOUT)
win32serviceutil.StartService(service)
if OS=='Windows':
try:
output = startByPython()
except subprocess.CalledProcessError as e:
print(e.output)
print(e.returncode)
#os.system('python test2.py')
subprocess.call("python ./install.py asadmin", shell=True)
startByCLI()
so what i actually want is i want to run the start method from command promt like this
python ./myfile.py startByPython
and it will trigger the startByPython method in myfile.py
many thanks in advance
Hey all thanks for your attention,
i wanted to run my file.py file with argument from command line like:
$ /usr/bin/python myfile.py start
i got the solution which is
def main():
# read arguments from the command line and
# check whether at least two elements were entered
if len(sys.argv) < 2:
print "Usage: python aws.py {start|stop}\n"
sys.exit(0)
else:
action = sys.argv[1]
if action == "start":
startInstance()
elif action == "stop":
stopInstance()
else:
print "Usage: python aws.py {start|stop}\n"
Goal.
When launching django framework also launch other PY scripts that rely on django objects.
Get the server and port number from a config file.
Problem:
The Popen seems to run twice and I'm not sure why?
#!/usr/bin/env python
import os
import sys
import subprocess
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.localsettings")
from django.core.management import execute_from_command_line
def getargs():
try:
f = open("config")
data = []
for line in f:
data.append(line)
f.close()
server = data[0].rstrip()
port = data[1]
newargs = ['lmanage.py', 'runserver', server + ':' + port]
return newargs
except Exception as e:
print e
pass
if __name__ == "__main__":
#Launching Checker
try:
checker = subprocess.Popen([sys.executable, os.path.join(os.getcwd() + "checker.py")], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print checker.pid
except Exception as e:
print e
pass
print "end"
execute_from_command_line(getargs())
Outputs:
16200
end
29716
end
Validating models...
This is my first attempt so if anyone knows of a better way to do this then feel free to let me know.
Thanks everyone.
Your code is launching the runserver command, which causes Django to use the reloader, which in turn means that your code is reexecuted as if it were entered on the command line. If you use --noreload when you launch runserver the issue will disappear.
So basically, the same facility that automatically reloads Django when you modify your source files, which is so useful in development, is now causing your code to execute twice.
I am a bit of a newbie on Python, but was was testing some things I learned on Ubuntu.
Basically, this script is supposed to set your TCP/IP config, then restart the networking daemon and display the changes.
This is the whole script:
#!/usr/bin/env python
import commands
import os
import sys
euid = os.geteuid()
if euid != 0:
print "Script not started as root. Running sudo.."
args = ['sudo', sys.executable] + sys.argv + [os.environ]
# the next line replaces the currently-running process with the sudo
os.execlpe('sudo', *args)
print 'Running. Your euid is', euid
print "IP"
IP = raw_input(">>")
print "Gateway"
PE = raw_input(">>")
ifconfig = commands.getoutput("ifconfig")
interfaz = ifconfig[0:5]
ArchivoInterfaces = open("/etc/network/interfaces", "w")
ArchivoInterfaces.write("#auto lo\n#iface lo inet loopback\nauto %s\niface %sinet static\naddress %s\ngateway %s\nnetmask 255.255.255.0"%(interfaz, interfaz, IP, PE))
ArchivoInterfaces.close()
ArchivoResolv = open("/etc/resolv.conf", "w")
ArchivoResolv.write("# Generated by NetworkManager\ndomain localdomain\nsearch localdomain\nnameserver 8.8.8.8\nnameserver 8.8.4.4")
ArchivoResolv.close()
os.execlpe('/etc/init.d/networking', "test","restart", os.environ)
print "Todo esta correcto, su IP ahora es %s" %(IP)
fin = raw_input("write d and press enter to show the changes, or press enter to exit.")
if fin == "d":
ArchivoResolv = open("/etc/resolv.conf")
ArchivoInterfaces = open("/etc/network/interfaces")
ifconfig2 = commands.getoutput("ifconfig")
print "ARCHIVO resolv.conf\n"+ArchivoResolv.read()+"\n\n"+"ARCHIVO interfaces\n"+ArchivoInterfaces.read()+"\n\n"+"RESULTADO DE \"ifconfig\"\n"+ifconfig2
fin = raw_input("Presiona ENTER para salir.")
Unfortunately, it keeps stopping on this line - and I'm not sure why:
os.execlpe('/etc/init.d/networking', "test","restart", os.environ)
After reaching this spot, the script runs the restart, and then just exits.
I would love to get it to run the last part of the script so I can see what changed, but I'm unable. Any ideas?
Because all of the exec family of functions work by replacing the current process with the one you execute.
If you just want to run an external command, use the spawn functions instead. (In this case, os.spawnlpe is very nearly a drop-in replacement.)
os.execlpe (and the similar os.exec* functions) replace the current process:
These functions all execute a new program, replacing the current process; they do not return.