I try to use python for get VM name on VMware (vSphere) when I execute this python script:
https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/get_vm_names.py
I have this message :
python3 test2.py --host ip_of_vmware
usage: test2.py [-h] -s HOST [-o PORT] -u USER [-p PASSWORD] [-S]
test2.py: error: the following arguments are required: -u/--user
I don't know how to execute this script.
I think this line which used to put in parameter:
si = SmartConnectNoSSL(host=args.host,
user=args.user,
pwd=args.password,
port=int(args.port))
atexit.register(Disconnect, si)
I want to know how to execute this script.
The arguments required for the program are built by setup_args function in that program which in turn appears to be constructed by this line:
parser = cli.build_arg_parser()
This is in a package I don't have so I can't see what it is doing.
Nevertheless the help message, without explicitly stating which arguments are mandatory, is hinting in that general direction. I believe the arguments in [ ] are optional and everything else is required, so you need at least -s HOST and -u USER
python3 test2.py -s HOST -u USER
or
python3 test2.py --host HOST --user USER
If you read message carefully it already tells how to use.
usage: test2.py [-h] -s HOST [-o PORT] -u USER [-p PASSWORD] [-S]
You need to pass all required arguments to run script successfully. Arguments given in [] means optional.
[-h] is to show the help message:
$ python get_vm_names.py -h
usage: get_vm_names.py [-h] -s HOST [-o PORT] -u USER [-p PASSWORD] [-nossl]
Arguments for talking to vCenter
options:
-h, --help show this help message and exit
standard arguments:
-s HOST, --host HOST vSphere service address to connect to
-o PORT, --port PORT Port to connect on
-u USER, --user USER User name to use when connecting to host
-p PASSWORD, --password PASSWORD
Password to use when connecting to host
-nossl, --disable-ssl-verification
Disable ssl host certificate verification
Look at the standard arguments in above message.
To run the script pass the arguments like this:
$ python get_vm_names.py -s <vSphere Server IP> -u <username> -p <Password>
or
$ python get_vm_names.py --host <vSphere Server IP> --user <username> --password <Password>
vSphere server IP, username and password are the same value which you use to connect to vSphere manually.
Related
I need to execute the following command from Python on Windows:
psql -h localhost -p 5432 -U postgres -f script.sql db_name
The above script works fine when ran from git bash / powershell. After entering the script in a terminal, I need to provide a password to confirm it (similar to when using sudo).
How can I do that? I keep finding solutions that I think are linux-based.
How do I do it on Windows? I have tried many variations of solutions involving subprocess, i.e:
import subprocess
p2 = subprocess.Popen(
'psql -h localhost -p 5432 -U postgres -f script.sql db_name',
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
print('this will print')
sudo_prompt = p2.communicate('THE_PASSWORD' + '\n')[1]
print('this will not')
A better option (more secure) than invoking psql with explicit mention of your password is to have a .pgpass file as described in the docs file (and keep it protected e.g. chmod 600 ~/.pgpass). This keeps your password out of the list of running processes.
On Windows:
On Microsoft Windows the file is named %APPDATA%\postgresql\pgpass.conf (where %APPDATA% refers to the Application Data subdirectory in the user's profile).
I am using fabric to automate some deployment stuff. Below is a sample of the code I used:
run(f"sudo -H -u www-data bash -c 'rm -r project_name' ")
run(f"sudo -H -u www-data bash -c '/opt/www-data/project-name/bin/pip install -r requirements.txt' ")
run("sudo systemctl stop gunicorn")
run("sudo systemctl start gunicorn")
Everytime each line of code was ran, the terminal ask for my user password, is there a way I can enter the password just once?
Edit:
I am using python3 and the essence of the script was to run the commands on a different user, rather than my own.
Update:
I achieved this by running fabric with "-I" param.
fabric -I deploy
Using run is not the ideal way to achieve this.
fabric.operations.sudo(*args, **kwargs) is something that can be used to achieve what you are attempting.
Please be careful with sudo :)
Every run() invocation is a separate shell, as would be a sudo() invocation. The sudo credentials are per shell, so they are gone every time.
A quick and dirty way would be to lump all commands into one sudo invocation.
A nicer way would be to have a sudoers file on the target host(s) and give each user the required privileges to run particular commands without entering a password.
You can create a fab script like below and then iterate over the host list you want to run the commands because you can passwd username and password in the script itself so to avoid password invocation:
# testCheck.py
#!/usr/bin/python2.7
import sys
from fabric.api import *
env.skip_bad_hosts=True
env.command_timeout=160
env.user = 'user_name'
env.shell = "/bin/sh -c"
env.warn_only = True
env.password = 'user_password'
def readhost():
env.hosts = [line.strip() for line in sys.stdin.readlines()]
def hosts():
with settings(warn_only=True):
output=sudo("ls -l /myfolder",shell=False)
# cat hostfile.txt| | /usr/local/bin/fab readhost -f testCheck.py hosts -P -z 5
OR supplying password at command line
# cat hostfile.txt | /usr/local/bin/fab readhost -f testCheck.py --password=your_pass hosts -P -z 5
--> argument "-P" refers to parallel execution method
--> argument "-z" refres to the number of concurrent processes to use in parallel mode
exapmle hostfile.txt:
server1
server2
server3
server4
Hope this will help.
If you are using ssh keys, then set the fabric environment variable key_filename:
env.key_filename='/path/to/key.pem'
# set the following as well
env.user='username'
env.host='hostaddr'
It will ask you for the password only one time.
Have a look at this question regarding avoid to enter any sudo password when using fabric.
I'm using pxssh to establish an SSH connection to a server. To connection can be establish and I can run simple commands such as ls -l.
What I need now is to create iptable entries via that SSH connection.
I've tried the following
s = pxssh.pxssh()
print(ip)
if not s.login(ip, username, auth_password):
Log("SSH session failed on login")
Log(str(s))
else:
Log("SSH session login successful")
cmd = 'sudo iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT;'
s.sendline(cmd)
s.prompt()
print(s.before)
s.logout()
which runs without error, but when connection to the server, no iptable entry had been created!?
Try modifying your python script like this:
cmd = '/usr/bin/sudo /usr/sbin/iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT'
s.sendline(cmd)
You should change the sudo and iptables path if it's different on your OS
Also try printing the s.sendline(cmd) to see what actually is executed via the ptyhon script on the server, just to be sure that the correct iptables command is executed
I am trying to import a pkcs#12 certificate into OS X Keychain using the following command:
security import filename -k ~/Library/Keychains/login.keychain -P password -f pkcs12
In python I use subprocess like this:
if os.path.isfile(_file) and platform.system() == 'Darwin':
keychain = os.path.expanduser('~/Library/Keychains/login.keychain')
command_line = 'security import {} -k {} -P {} -f pkcs12'.format(_file, keychain, password)
logger.info('Importing {} into OS X KeyChain.'.format(_file))
return subprocess.call(shlex.split(command_line))
However I get this error message:
security: SecKeychainItemImport: One or more parameters passed to a function were not valid.
I even tried using shell=True but I then I got the security usage back as if I had passed some wrong argument.
Usage: security [-h] [-i] [-l] [-p prompt] [-q] [-v] [command] [opt ...]
...
...
However, when running it from the command line, the command works as expected:
security import <filename> -k <home>/Library/Keychains/login.keychain -P DTWLDHPYNBWBJB3 -f pkcs12
1 identity imported.
1 certificate imported.
Any idea? Is there a restriction when running security from a non interactive console?
Any python library to achieve the same?
Regards
This was actually due to another problem.
I was using a tmpfile which was not being flushed or closed.
While the script was running the function could not find any content on that file.
Once the script ended, the file (which had 'delete=False') was flushed and for this reason the command line was working no problem.
Solution was to set bufsize=0 :(
In all my scripts I use the standard flags --help and --version, however I cannot seem to figure out how to make a --version with parser.add_argument(..., required=True).
import sys, os, argparse
parser = argparse.ArgumentParser(description='How to get --version to work?')
parser.add_argument('--version', action='store_true',
help='print version information')
parser.add_argument('-H', '--hostname', dest='hostname', required=True,
help='Host name, IP Address')
parser.add_argument('-d', '--database', dest='database', required=True,
help='Check database with indicated name')
parser.add_argument('-u', '--username', dest='username', required=True,
help='connect using the indicated username')
parser.add_argument('-p', '--password', dest='password', required=True,
help='use the password to authenticate the connection')
args = parser.parse_args()
if args.version == True:
print 'Version information here'
$ ./arg.py --version
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD
arg.py: error: argument -H/--hostname is required
Yes, I want --hostname and others required, but I always want --version to work appropriately like --help (and -h).
$ ./arg.py --help
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD
How to get --version to work?
optional arguments:
-h, --help show this help message and exit
--version print version information
-H HOSTNAME, --hostname HOSTNAME
Host name, IP Address
-d DATABASE, --database DATABASE
Check database with indicated name
-u USERNAME, --username USERNAME
connect using the indicated username
-p PASSWORD, --password PASSWORD
use the password to authenticate the connection
Any help on getting --version to work?
There is a special version action keyword argument to add_argument (As documented here: argparse#action).
Try this (copied from working code):
parser.add_argument('-V', '--version',
action='version',
version='%(prog)s (version 0.1)')