Set & Get environment variables in python

In bash generally we export environment variables like :

export VARIABLE=value

In some cases in our we need to set some environment variables inside our python programme to use it further.

But in Python, the if we try to use the system call to set the variable it never works :

e.g.

import os

os.system(‘export VARIABLE=value’)

It never works as, the python is the child process of bash and it cant change the env variable of Parent bash.

So here we have to use:

import os

os.environ[‘VARIABLE’] = “value”

To get the values of any environment variable :

import os

value=os.getenv(“VARIABLE”)

Python pexpect – (password and password less authentication by ssh and do remote task)

This code use pexpect module of python to perform the operation.

 

[code language=”python”]

#v1.0 – to supply password and login

import sys
import pexpect

user = ‘user’
password = ‘password’
host = ‘host1.us.com’
command = ‘hostname ; echo $?’
def dossh(user, password, host, command):
child = pexpect.spawn(‘ssh %s@%s %s’ % (user,host,command),logfile=sys.stdout,timeout=None)
prompt = child.expect([‘password:’, r"yes/no",pexpect.EOF])
if prompt == 0:
child.sendline(password)
elif prompt == 1:
child.sendline("yes")
child.expect("password:", timeout=30)
child.sendline(password)
data = child.read()
print data
child.close()

dossh(user, password, host, command)

[/code]

Using the sys module this can be further enhanced to pass the arguments in argv[n].

Here logs will be written in stdout but it can be changed to any logfile.

Also this can be modified to perofrm scp operation or any othere complex command on remote server. Correct the indentation after copying the code.

or any other expected prompt can be added in the  list and value can be passed as required.

Its enhanced here to handle passwordless authentication as well.

[code language=”python”]
#!/usr/bin/env python
#v1.1 – To handle both password and passwordless authentication
import sys
import pexpect

user = ‘user1’
password = ‘welcome1’
host = sys.argv[1]
command = ‘hostname; whoami; echo $?’

def dossh(user,password,host,command):
try:
child = pexpect.spawn("ssh -o ServerAliveInterval=100 -n %s@%s ‘%s’" % (user,host,command),logfile=sys.stdout,timeout=None)
i = child.expect([‘password:’, r’\(yes\/no\)’,r’.*[$#] ‘,pexpect.EOF])
if i == 0:
child.sendline(password)
elif i == 1:
child.sendline("yes")
ret1 = child.expect(["password:",pexpect.EOF])
if ret1 == 0:
child.sendline(password)
else:
pass
else:
pass
data = child.read()
print data
child.close()
return True
except Exception as error:
print error
return False

dossh(user, password, host, command)
[/code]