Wednesday, December 7, 2011

Input DB2 password using Python openpty()

Here is how to use python openpty() to input DB2 password.
  • You need use openpty() because db2 insists reading from a terminal. You cannot use PIPE for stdin to pass the password.
  • You have to read from stdout first. If you write the password through pty before reading, db2 may not read the password because it needs time to start.
  • In python, read() will read until EOF. readline() won't work in that db2 prints "Enter " and waits for the input, no new line is present yet.
import os
import subprocess

m,s = os.openpty()
print m,s
p = subprocess.Popen("db2.sh", stdin=s, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
f = os.fdopen(m, "w")
out = p.stdout.read(5)
print "OUT: %s" % out
if out == "Enter":
  f.write("mypassword\n")
else:
  exit(-1)

print "\nSTDOUT:\n"
for line in p.stdout:
  print line
print "\nSTDERR:\n"
for line in p.stderr:
  print line
print p.returncode
#!/bin/bash
set -e
source /home/db2c97/sqllib/db2profile
db2 connect to DEVEDW user myname
echo $?
echo "loading ..."
db2 "select count(*) from players"
echo $?

No comments:

Post a Comment