Folks
I am not very up with Python but have inherited a load of Python scripts
One of which is given me a issue in that I am not 100% sure what one line is running
What I need to do is print out the command line and its variables.
The line in question is
ldapModify(userdn, mods, uri=uri)
What I am hoping to see is something like
/usr/bin/ldapmodify xxxx cn=......
Can any kind soul help.
The Python ldap lib doesn't call on the ldap command line client, it binds directly to the underlying system ldap lib.
If what you want is to know the values of the args passed to ldapModify, it's quite simple: print them to sys.stderr :
import sys
try:
ldapModify(userdn,mods,uri=uri)
except Exception, e:
print >> sys.stderr, "oops, ldapModify failed with '%s'" % e
print >> sys.stderr, "userdns : '%s' - uri : '%s' - mods : '%s'" % (userdns, uri, mods)
# and reraise the error so you get the whole traceback
raise
Before the line in question, you could place a call to python's interactive debugger. Then you can print out the variables in question:
import pdb
pdb.set_trace()
ldapModify(userdn, mods, uri=uri)
At the (pdb) prompt you can print out the value of any or all of the variables.
Here's a link about the debugger.
Related
I am working on a code so that it can handle the error from fabric.local, but some how it always abort with the error and never go into except block.
Here is my code, hopefully can get some idea from you guys
This snippet is trying to get Vagrant ssh port, if the vagrant is not up, bring it up
def findsshport():
with settings(warn_only=True):
try:
print 'greping port'
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
except:
print 'vagrant not up'
with lcd('%s' % (buildfolder)):
local('vagrant up ext4')
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
env.user = 'root'
sshPort = findsshport()
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
Error
[localhost] local: vagrant ssh-config 22921a7 | grep Port
Warning: local() encountered an error (return code 1) while executing 'vagrant ssh-config 22921a7 | grep Port'
Traceback (most recent call last):
File "/home/testing/local/lib/python2.7/site-packages/test123/fabriclogin.py", line 114, in sshlogin
env.hosts = ['127.0.0.1:' + sshPort.split()[1]]
AttributeError: 'NoneType' object has no attribute 'split'
UPDATE
Similar Question and Answer
Can I catch error codes when using Fabric to run() calls in a remote shell?
It seems like it's just a warning from fabric. My understand if you encounter an error on ssh, it doesn't "translate" into a Python error, that's why the exception block doesn't work. Please provide error trace for further analysis.
Martin is correct, that was a warning from fabric.api.local and python exception handling will not treat it as an error. Instead, the error that I seen was from another part of code which the above snippet had returned something invalid.
Instead of using try and except, if else is used with return_code which checking the command exit status.
port = local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True)
if port.return_code == 0:
return port
else:
with lcd('%s' % (buildfolder)):
local('vagrant up {}'.format(env.vmId), capture=True)
return (local('vagrant ssh-config {} | grep Port'.format(env.vmId), capture=True))
Your problem is probably here.
with settings(warn_only=True)
Remove this line, and your local call will raise exceptions if the command exits with a non-zero return code.
def task_name():
with settings(warn_only=True):
try:
local("invalid_command")
except:
print("This will never print!")
Lets compare that to;
def task_name():
try:
local("invalid_command")
except:
print("This will print")
What is the best way to translate the following MATLAB command to Python?
[~,hostname] = system('hostname');
You're looking for gethostname() from thesocket interface, which is "available on all modern Unix systems, Windows, MacOS, and probably additional platforms." (from the docs):
>>> import socket
>>> socket.gethostname()
'DK07'
If gethostname() fails for some reason, it would raise an exception. That is different however from if the name is omitted or empty, in which case it is interpreted as the local host.
Another portable equivalent (just for the sake of completeness) is
>>> import platform
>>> platform.node()
'DK07'
You should also take a look at Cong Ma's answer for a good example.
To give an example on Kong's explanation, you can always wrap the syscall inside a try block like this:
import sys
import errno
try:
hostname = socket.gethostname()
except socket.error as s_err:
print >> sys.stderr, ("error: gethostname: error %d (%s): %s" %
(s_err.errno, errno.errorcode[s_err.errno],
s_err.strerror))
This will format the error information as something like error: gethostname: error 13 (EACCES): Permission denied, although this is just a hypothetical situation.
If you want to use an external process in the way system() does (but without spawning a shell), you can execute a command using subprocess:
import subprocess
cmd = subprocess.Popen(["hostname"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmdout, cmderr = cmd.communicate()
print "Command exited with code %d" % cmd.returncode
print "Command output: %s" % cmdout
I am using python-daemon in my code that has print statements in it. I want to send them to a file so I ran the following:
python server.py >> log.out
However, nothing goes in log.out.
Can anyone tell me what I need to do?
Thanks.
The DaemonContext object allows redirecting stdout/stderr/stdin when you create the object. For example:
import os
import daemon
if __name__ == '__main__':
here = os.path.dirname(os.path.abspath(__file__))
out = open('checking_print.log', 'w+')
with daemon.DaemonContext(working_directory=here, stdout=out):
for i in range(1, 1000):
print('Counting ... %s' % i)
You should be able to cat checking_print.log and see the output from the print statements.
A good reference for the DaemonContext object is PEP 3143.
if you have an error in your code it will not be written to the file. See http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html
Try creating this file:
print 'stdout'
raise Exception('stderr')
If it's already running as a daemon you'll most likely need to force redirection of STDOUT, STDERR etc. You can read more on I/O Redirection here.
python server.py 2>log.out >&2
Need assistance with the pexpect module
I have written a simple code which would clone a git repository from a server using ssh.
I'm facing couple of problems.
The password is shown in plain text.
I dont know a proper way to exit the program after the download. it throws out the following error...
Traceback (most recent call last):
File "ToDelete3.py", line 65, in <module>
# # if i == 1:
File "ToDelete3.py", line 36, in getRepository
i = p.expect([ssh_key,'password:',pexpect.EOF])
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1492, in interact
self.__interact_copy(escape_character, input_filter, output_filter)
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1520, in __interact_copy
data = self.__interact_read(self.child_fd)
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 1510, in __interact_read
return os.read(fd, 1000)
OSError: [Errno 5] Input/output error
the code that I have written so far is :
command = 'git clone ssh://username#someserver/something.git'
ssh_key = 'Are you sure you want to continue connecting'
def gracefulExit():
print 'Password Incorrect !!!'
os._exit(1)
def getRepository():
p = pexpect.spawn(command,maxread=10000,timeout = 100)
p.logfile = sys.stdout # logs out the command
i = p.expect([ssh_key,'password:',pexpect.EOF])
if i == 0:
print 'Inside sshkey'
p.sendline('yes')
i = p.expect([ssh_key,'password:',pexpect.EOF])
if i == 1:
try:
p.sendline('mypassword') # this mypassword is shown in clear text on the console
p.interact()
p.logfile = sys.stdout
p.expect(pexpect.EOF)
except Exception,e:
print str(e)
gracefulExit()
if i == 2:
print 'Inside EOF block'
if p.isalive():
print '******************************************************'
print ' Closing the process of Download !!! '
print '******************************************************\n\n'
p.close()
Any inputs is highly appreciated..
Thanks.
-Vijay
There are few errors in the program:
p.interact()
This is used when we want to get back the control after having automatically supplied the password using pexpect module. You don't need to use that since you are automating the whole repository check out.
Also a few things can be improved, after passing the password, set a infinite timeout since it may take a while to copy a git repository.
p.expect(pexpect.EOF, timeout=None)
After that you can read all the execution output with the following command
output_lines = p.before
output_lines_list = output_lines.split('\r\n')
for line in output_lines: print line
you can also use the above to log the output to a file by directly writing to it
Using p.logifile = sys.stdout is not good since it will record pexpect operation from start including passing of password.
After this there is no need to close, you are not running a interactive program. Remove all these lines:
if i == 2:
print 'Inside EOF block'
if p.isalive():
print '******************************************************'
print ' Closing the process of Download !!! '
print '******************************************************\n\n'
p.close()
The issue is that some where you have to store the password and use it with p.sendline. How ever, you store password, it is going to be insecure. You can also take the input at the start for the password, this way you will not be storing the password within your program but that defeats automation. I don't see a way out but for taking password input, you can do:
import getpass
getpass.getpass("please provide your password")
To get rid of the password being echo'd to stdout, use the following when redirecting output -
p.logfile_read = sys.stdout # logs out the command
I have tried this myself and seems to be working. Here is the reference for this revelation.
I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks
#!/home/build/test/Python-2.6.4
import os, subprocess
class mks_function:
sandbox="new_sandbox"
def mks_create_sandbox():
try:
retcode=call("si createsandbox" + "--no --hostname=bel --port=70 --user=user --password=1234 --populate --project=e:/project.pj --lineTerminator=lf new_sandbox", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
print "sandbox retVal="+retcode
print "Creating a new sandbox called "+sandbox+" "
###############################################################
Few things to check your code
call should be subprocess.call
better use full path when you call for example, /usr/bin/si createsandbox, you can check with which si in shell
instead of concatenating the commands "si createsandbox" + "--no ...", please use list ["/usr/bin/si","createsandbox --no ..."]
you didn't import sys, but using it
sandbox should be self.sandbox and def mks_create_sandbox(): should be def mks_create_sandbox(self):
Use an IDE for example Ulipad.
Try put as the first line:
#!/usr/bin/env python
If you really need specific version of Python, setup your environment before running.
Possible problems:
your code is never executed (it's like you define the class only). Use it in the file (names are misleading):
if __name__ == '__main__':
myObject = mks_function()
show us how are you executing the code? Have you changed the permissions to be able to run the script?
chmod +x filename.py
or are you trying to start it as:
python filename.py