How to enter the requested data in the terminal - python

I had a problem entering the password directly through the python program
When I do something in PostgreSQL, it asks for a database password and here
How can I enter the database password through python so that it is entered in the requested field
pg_dump.exe -U dbuser -h localhost dbname >> s.sql
>>>Password:
I know that there is a .pgpass file, but there is a possibility of frequent password changes

Related

How do I SSH to machine through a middle host using Paramiko?

Essentially, I need to access a computer, say machine A, which is only accessible via the internal network of my company. I used to be able to set up tcprelay port forwarding to accomplish this but that pipeline has been disabled due to some potential security flaws.
Let’s say my company general network is at
company#10.0.0.1
and the specific machine i want to work with is at
machine#10.0.0.3
Both accounts have password ‘password’
Via terminal and shell commands, I can just hop there using one single command:
https://askubuntu.com/a/311457
or, in steps, it would be:
[on my account] ssh company#10.0.0.1
[on my account] enter password
[on company network] ssh machine #10.0.0.3
[on company network] enter password again
And I’d be logged into the machine I need to communicate with.
However, after hacking away all afternoon I could not get this working with Paramiko. I tried setting up the connection then issuing a client.exec_command() but just cannot get a handle for the specific machine. The rest of my scripts relies on having a paramiko client that can receive commands and return responses, so it would be a very heavy overhead for me to go propagate all changes were I to switch to say fabric or subprocess.
The closest I got to was:
ssh.connect(’10.0.0.1', username=‘company', password=‘password’)
chan = ssh.get_transport().open_session()
chan.get_pty()
chan.exec_command(‘ssh machine#10.0.0.3’)
print chan.recv(1024)
which returned the ‘enter password’ prompt, but running chan.send(‘password’) just ends with a hang.
I’m pulling my hair out at this point and am just reading through the documentation hoping to find what concept I’m missing.
If anyone can give some advice I’d really appreciate it.
Thanks!
Alternative way is to avoid entering password when login to another machine.
This can be done by using ssh-keygen.
Login to first machine (A) with user 'first':
$ ssh-keygen -t rsa
--> Don't enter any passphrase when requested
--> Note down the line "Your public key has been saved in /home/first/.ssh/"
--> This file is the public key of machine 'A'
Now login to second machine(B) using ssh.
Then check for ~/.ssh folder. If no folder, create one.
Create a file with name 'authorized_keys' under ~/.ssh/authorized_keys
Copy the content of file from 'first' user to the file 'authorized_keys'.
is a file with 'id_rsa.pub' from 'first' user login (under /home/first/.ssh/id_rsa.pub)
Now you can login to second machine from first without entering password thru your script.
I worked on a project where it had to log in using username/password over SSH then do the same thing again to another host. I had no control over networks ACLs and SSH keys were not allowed for some reason. You'll need to add paramiko_expect. Here's how I got it to work:
import paramiko
from paramiko_expect import SSHClientInteraction
user1 = 'admin'
pass1 = 'admin'
user2 = 'root'
pass2 = 'root'
# not needed for this example, but included for reference
user_prompt = '.*\$ '
# will match root user prompt
root_prompt = '.*$ '
# will match Password: or password:
pass_prompt = '.*assword: '
# SSH to host1
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh_client.connect(hostname='host1', username=user1, password=pass1)
# Interact with SSH client
with SSHClientInteraction(ssh_client, display=True) as interact:
# Send the command to SSH as root to the final host
interact.send('ssh {}#host2'.format(user2)
# Expect the password prompt
interact.expect(pass_prompt)
# Send the root password
interact.send(pass2)
# Expect the root prompt
interact.expect(root_prompt)
ssh_client.close()
One caveat: if host1 has never connected to host2 using SSH it'll get a warning about host key checking and timeout. You can change the configuration on host1 or just SSH to host1 then from host1 SSH to host2 and type yes and press enter.

Python Fabric capture interactive dialog output

I would like to use Fabric to set the password for a user on a remote server.
Let's say I have a user named 'john' and I want to set a default password '123' for him.
Ideally I would like to do this:
run 'passwd john' on remote machine
detect when linux prompts for 'Enter new UNIX password:'
automatically enters the password
detect when linux prompts for 'Retype new UNIX password:'
automatically reenters the password
This is what I have tried:
result = run('passwd {}'.format(username))
The problem with this statement is that 'result' does not capture when Linux prompts for entering password. It only returns after the passwords are entered.
Is there a way to automate interactive prompts like this?
you can use prompts
password = '123'
with settings(prompts={
'Enter new UNIX password: ': password,
'Retype new UNIX password: ': password
}):
run('passwd {}'.format(username))
You can use fexpect for interactive prompts.

Unable to use database in mysql (access denied)

I am trying to get started with the following github package: py-gameday.
I installed mysql with brew mysql and created a root password:
> mysqladmin -u root password 'xxx'
I then created a user:
> mysql -uroot -p
Enter password: xxx
CREATE USER 'josh'#'localhost' IDENTIFIED BY 'yyy';
Just in case, I reset the password again:
SET PASSWORD FOR 'josh'#'localhost' = PASSWORD('yyy');
and I then updated mydb.ini with:
[db]
user=josh
password=yyy
db=gameday
I finally tried running the following:
$ mysql -D gameday < gameday.sql -p
Enter password:
ERROR 1044 (42000): Access denied for user 'josh'#'localhost' to database 'gameday'
In this last step, I tried entering 'xxx' and 'yyy', but none of them worked. Why?
You need to GRANT access for the user 'josh' to the database 'test'.
GRANT ALL ON test.* TO 'josh'#'localhost';
As long as you don't have NO_AUTO_CREATE_USER set, you can skip the CREATE USER... the following will create the USER and GRANT access in one hit...
GRANT ALL ON test.* TO 'josh'#'localhost' IDENTIFIED BY 'yyy';
You have to also set privileges for that user
GRANT ALL ON test.* TO 'josh'#'localhost';

mysql setting user name and password

I have just installed mysql on Mac OSX and can easily open it in a shell and gain access to the databases and tables that come with it.
Now I want to create a database in Python using mysql-connector/python
Before doing that I figured it would be wise to set a user name and password in mysql.
I have tried using the following but get error messages.
My GOAL is to set a user name and a password so that I may simply provide it to mysql-connector for python, and ultimately execute sql queries from the python environment. Here is what I tried at the mysql command prompt:
SET PASSWORD FOR 'root'#'localhost' = PASSWORD('newpwd');
And I get the error message:
ERROR 1044 (42000): Access denied for user ''#'localhost' to database 'mysql'
So I tried the UPDATE METHOD:
UPDATE mysql.user SET Password = PASSWORD('newpwd')
WHERE User = 'root';
and I get the error message:
ERROR 1142 (42000): UPDATE command denied to user ''#'localhost' for table 'user'
So does anyone know why I get denied and how I can make the changes to create a user and a password that I may ultimately use in mysql connect in the python environment?
Sounds like you are not properly authenticated. Make sure you are authenticated with root user
Access denied for user ''#'localhost' to database 'mysql'
should look like
Access denied for user 'root'#'localhost' to database 'mysql'
Otherwise you are not logged in as root, but rather as an anonymous user.
Ofc, when you are logged in with root, you won'T get that message, but you would get it for any username that does not have the proper rights.
start your query with authentication
mysql -u USERNAME -pPASSWORD -h HOSTNAMEORIP DATABASENAME
example:
mysql --port=3307 --host=127.0.0.1 -u root --password=thisismypass test -e "LOAD DATA LOW_PRIORITY LOCAL INFILE '%pathuser%' INTO TABLE `user_log`...."
in your case probably
mysql -u root "SET PASSWORD FOR 'root'#'localhost' = PASSWORD('newpwd');"

MySql Python connect

I'm trying to connect python with MySQL, but I get this error:
OperationalError: (1045, "Access denied for user 'root'#'localhost' (using password: NO)")
I'm trying to solve it for 6 hours and I fail. Can any one please help me ?
it means that you forgot the password parameter, which in mysql is not required.
from a unix command line:
$ mysql -u root
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: NO)
$ mysql -u root -p
Enter password:
<typing password>
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 47
Server version: 5.1.37-1ubuntu5.5 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
not exactly the same as logging from python,
but it's the same error, and most likely means that in your case the password argument did not make it to mysql at all.
when I type the wrong password I get a very different error on the command line:
$ mysql -u root -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: YES)
You didn't specified your root password.
If you are accessing mysql from remote computer... root user is by default limited to localhost connections only. Try running this to enable access from anywhere:
GRANT ALL PRIVILEGES ON *.* TO root#'%' IDENTIFIED BY "YOUR_ROOT_PASSWORD";
FLUSH PRIVILEGES;
Also check your firewall settings.
import MySQLdb
cxn = MySQLdb.connect(host = 'localhost',user = 'root',passwd = 'password', db = 'yourdatabase')
So you need to know what your password is and you need to have created a database with:
CREATE DATABASE yourdatabase;
from the mysql command line as described above.
I was getting this error because I had quotes in my config file.
[mysql]
username: 'uuuu'
password: 'pppp'
host: 'localhost'
database: 'dddd'
should have been
[mysql]
username: uuuu
password: pppp
host: localhost
database: dddd
If you don't see any value in front of the password column when you do
SELECT user, host, password FROM mysql.user;
within your mysql
In your python script don't specify the password
for example
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your password
db="dynamo",
port = 3306) # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("select * from SomeTable limit 10")
# print all the first cell of all the rows
for row in cur.fetchall():
print(row[0])
db.close()

Categories

Resources