Cant connect to database pymysql using a .my.cnf file - sql

This function should connect to database because I've used an exception I'll get my own created message, when incorrect input is found. But when I remove try and except I get : "Acces denied for /'user/'#'/'localhost' (using password : NO).
It seems that it doesnt read my password I have no clue why a little help will be appreciated. Without this file connection to the database works fine without any errors.
try:
self.conn = pymysql.connect(read_default_file="~/my.cnf")
self.curr = self.conn.cursor()
except pymysql.err.OperationalError :
sys.exit("Invalid Input: Wrong username/database or password found, please try again")
Information found in the .my.cnf file is :
[client]
host = 'localhost'
port = 3306
user = myusername
password = "mypassword"

You used:
pymysql.connect(read_default_file="~/my.cnf")
You should have used:
pymysql.connect(read_default_file='~/.my.cnf')
-------------------------------------^
Note the missing dot in the filename. You were just loading a different or non existent file.
The ~ is being expanded as shown here:
https://github.com/PyMySQL/PyMySQL/blob/18b62f6e1d6f65b403c9e8b650f4c3bb27b665e7/pymysql/connections.py#L619
Also I can confirm that no quotes or spaces are required in the .my.cnf file:
echo -e "[client]\nuser=root\npassword=defaultrootpwd" > ~/.my.cnf

First off, can you connect to your database using the following command.
import pymysql
conn = pymysql.connect(host='localhost',
port=3306,
user='myusername',
passwd='mypasswd')
If that doesn't work, then you might have some other problem (for instance, your database may be configured to only connect via socket for local clients)
As for the config file, I think this will work if you remove the quotation marks, like this:
[client]
host = localhost
port = 3306
user = myusername
password = mypassword
I saved your config file as test.cnf and ran the following code
# test.cnf
[client]
host = 'localhost'
port = 3306
user = myusername
password = "mypassword"
$ python3
>>> import configparser
>>> reader = configparser.RawConfigParser()
>>> reader.read('test.cnf')
>>> reader.get('client', 'host')
"'localhost'"
>>> reader.get('client', 'user')
'myusername'
As you can see, the config parser is treating quotes as part of the value.
Update: Workaround
The OP mentioned the provided solution (i.e. removal of quotes did not solve the problem he was facing). Here's a workaround that achieves separation of configuration / connection properties from program logic.
Save the configuration in a python file called dbsettings.py.
# dbsettings.py
connection_properties = {
'host': 'localhost',
'port': 3306,
'user': 'myusername',
'passwd': 'mypassword'
}
And then in your main program use the following lines for setting up the connection.
try:
from dbsettings import connection_properties
self.conn = pymysql.connect(**connection_properties)
self.curr = self.conn.cursor()
except pymysql.err.OperationalError :
sys.exit("Invalid Input: Wrong username/database or password found, please try again")
If your entire program is written in python, then this allows the same separation of connection / config info from program logic as using the my.cnf method, and it is just as flexible if not mroe so. However, if other non python scripts need to reference the my.cnf file, then you'll have to maintain two separate mysql config files.

Related

ftplib.error_perm: 550 Create directory operation failed while using FTP_TLS

I am trying to connect to a secure FTP server created based on this link. I have not followed step 8 in the link. I am able to establish the connection and also change and print directories but am unable to create new directories. I am also unable to fetch files list.
Here is my code snippet:
import ssl
from ftplib import FTP_TLS
import sys
import os
import os.path
def connect():
ftp = FTP_TLS()
ftp.debugging = 2
ftp.connect('ipaddress', 21)
ftp.set_pasv(False)
ftp.login('user', 'passwd')
return ftp
ftps = connect()
destdir = "/"
try:
resp = ftps.pwd()
ftps.cwd(destdir)
except Exception:
ftps.mkd(destdir)
print(resp)
root = 'C:\\Users\\****\\****\\Logs' # local dir
for (dir, _, files) in os.walk(root):
newdir = destdir+dir[len(root):len(dir)].replace("\\", "/")
print(newdir)
try:
ftps.cwd(newdir)
except Exception:
ftps.mkd(newdir)
I am using python 3.7.3 and the corresponding ftplib. I would be happy to provide any other details required.
PS: I am able to connect with Filezilla and create directories.
This is the error after running.
I am able to create the directories successfully once I change the dir to /logs. I am getting an error "ftplib.error_perm: 500 Illegal PORT command." whenever I send cmd like retrlines or storbinary
, I get this error
I have searched about this and people have asked to set it to pasv mode. When I do that, I get this error. FYI, I have enabled pasv mode in the config file
I tried changing the port number to a number between pasv ports enabled in the config file (between 30000-31000). It does not connect also in this case. Error returned "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
I am working the first time with an FTP server or for that matter any server communications, so my problems might seem trivial. I am sorry for your trouble.
Thanks.

bWAPP on my live webserver is tossing me an sql error

I am trying to put bWAPP on my spare webserver for me and my friends to use.
It's locked by a password and stuff, so only people who know it can use it.
Here's the configuration I have right now.
$db_server = "atroxis.net";
$db_username = "ethereal_atrox";
$db_password = "(redacted)";
$db_name = "ethereal_bwapp";
The password is right, I just redacted it.
I keep getting this SQL error.
Connection failed: Access denied for user 'ethereal_atrox'#'51.38.85.24' (using password: YES)
Anyone have any ideas?
Try to put:
$db_server = "localhost";
and reload apache.
If it doesn't work, verify the file connect.php and change myql_ for mysqli_

Using Ansible on windows with domain user

I'm starting to learn Ansible but the documentation is not too helpful.
I have installed the control machine on RHEL and created the necessary hosts file and windows.yml.
But when trying to connect to the remote Windows server to get a pong back I get the following error:
[root#myd666 ansible_test]# ansible windows -i hosts -m win_ping
hostname | UNREACHABLE! => {
"changed": false,
"msg": "ssl: the specified credentials were rejected by the server",
"unreachable": true
}
After Installing python-kerberos dependencies,
I now get this Error:
hostname | UNREACHABLE! => {
"changed": false,
"msg": "Kerberos auth failure: kinit: KDC reply did not match expectations while getting initial credentials",
"unreachable": true
}
My windows.yml file contains:
# it is suggested that these be encrypted with ansible-vault:
# ansible-vault edit group_vars/windows.yml
ansible_ssh_user: user#MYDOMAIN.NET
ansible_ssh_pass: password
ansible_ssh_port: 5986
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
Am I doing anything wrong with the syntax of Domain\user? Maybe I forgot to install something on the Windows machine? I only ran the ConfigureRemotingForAnsible.ps1 script, and Python is not installed there.
This is my krb5.conf file:
[libdefaults]
default_realm = MYDOMAIN.NET
#dns_lookup_realm = true
#dns_lookup_kdc = true
[realms]
MYDOMAIN.NET = {
kdc = dc1.mydomain.net
default_domain = hpeswlab.net
}
[domain_realm]
.mydomain.net = MYDOMAIN.NET
mydomain.net = MYDOMAIN.NET
And I do get a token using Kinit:
kinit -C user#MYDOMAIN.NET
klist
Klist output:
Valid starting Expires Service principal
01/31/2017 11:25:33 01/31/2017 21:25:33 krbtgt/MYDOMAIN.NET#MYDOMAIN.NET
renew until 02/01/2017 11:25:29
In windows.yml, please double-check and ensure that the ansible_ssh_user: user#MYDOMAIN.NET line does indeed have the realm MYDOMAIN.NET in upper case. Somewhere, the realm request to the KDC is being sent in lower case instead of upper case causing the 'KDC reply did not match expectations..' error.
In krb5.conf, case-sensitivity is also important. First I'll note that since the KDC name is the name of an IP host, so it needs to be specified as a fully-qualified host name, like in the example shown below. It assumes your KDC is named "dc1.mydomain.net". Next, the domain name should only be in lower case. On the other hand, Kerberos Realm names need be in upper case - if the realm name is incorrectly specified in lower case in this file that is another reason you may get this error message. Please modify your entire krb5.conf to look like that shown below (changing only "dc1" to the actual name) and it should work. Side note: You do not necessarily need the two dns_lookup_ lines in your krb5.conf, so please comment them out per the below. Those are fallback mechanisms only as per the MIT Kerberos Documentation and may actually cause issues in your simple use case. After modifying either configuration file, make sure to restart the Ansible engine before testing again.
[libdefaults]
default_realm = MYDOMAIN.NET
#dns_lookup_realm = true
#dns_lookup_kdc = true
[realms]
MYDOMAIN.NET = {
kdc = dc1.mydomain.net
default_domain = mydomain.net
}
[domain_realm]
.mydomain.net = MYDOMAIN.NET
mydomain.net = MYDOMAIN.NET
Please refer to this MIT reference for how to properly set up the krb5.conf: Sample krb5.conf File
In the Hosts file, check to ensure your IP to name mappings are correct. Per the RFCs, Kerberos requires a properly functioning DNS, and you are at risk of shortchanging that if your Hosts file has outdated entries in it.
Finally, though I wasn't able to tell which version of Ansible you were using, I did some research and found that "Ansible 2.0 has deprecated the “ssh” from ansible_ssh_user, ansible_ssh_host, and ansible_ssh_port to become ansible_user, ansible_host, and ansible_port." This could certainly be part of the problem. See: Ansible on Windows Documentation

Only show repos in gitweb that user has access to via Gitolite

I have gitolite setup and working with SSH key based auth. I can control access to repos via the gitolite-admin.git repo and the conf file. All of this works great over SSH but I would like to use GitWeb as a quick way to view the repos.
GitWeb is working great now but shows all repositories via the web interface. So my goal here is to:
Authenticate users in apache2 via PAM, I already have the Ubuntu server authenticating aginst AD and all the users are available. This should not be an issue.
Use the user name logged in with the check gitolite permissions
Display apropriate REPOS in the web interface.
Does anyone have a starting point for this? The Apache part shouldn't be difficult, and I'll set it to auth all fo the /gitweb/ url. I dont know how to pass that username around and authorize it against gitolite. Any ideas?
Thanks,
Nathan
Yes, it is possible, but you need to complete the gitweb config scripts in order to call gitolite.
The key is in the gitweb_config.perl: if that file exists, gitweb will include and call it.
See my gitweb/gitweb_config.perl file:
our $home_link_str = "ITSVC projects";
our $site_name = "ITSVC Gitweb";
use lib (".");
require "gitweb.conf.pl";
In gitweb/gitweb.conf.pl (custom script), I define the official callback function called by gitweb: export_auth_hook: that function will call gitolite.
use Gitolite::Common;
use Gitolite::Conf::Load;
#$ENV{GL_USER} = $cgi->remote_user || "gitweb";
$export_auth_hook = sub {
my $repo = shift;
my $user = $ENV{GL_USER};
# gitweb passes us the full repo path; so we strip the beginning
# and the end, to get the repo name as it is specified in gitolite conf
return unless $repo =~ s/^\Q$projectroot\E\/?(.+)\.git$/$1/;
# check for (at least) "R" permission
my $ret = &access( $repo, $user, 'R', 'any' );
my $res = $ret !~ /DENIED/;
return ($ret !~ /DENIED/);
};
From the comments:
GL_USER is set because of the line:
$ENV{GL_USER} = $cgi->remote_user || "gitweb";
$cgi->remote_user will pick the environment REMOTE_USER set by any Apache Auth module which has completed the authentication (like in this Apache configuration file).
You can print it with a 'die' line.
"Could not find Gitolite/Rc.pm" means the INC variable used by perl doesn't contain $ENV{GL_LIBDIR}; (set to ~/gitolite/lib or <any_place_where_gitolite_was_installed>/lib).
That is why there is a line in the same gitweb/gitweb.conf.pl file which adds that to INC:
unshift #INC, $ENV{GL_LIBDIR};
use lib $ENV{GL_LIBDIR};
use Gitolite::Rc;
Edit from Nat45928: in my case I needed to insert my home path into all the '#H#' entries. That solved all of my issues right away.

Creating user in Jenkins via API

I was wondering if I can create a new user in Jenkins using its API. I can create jobs but the API docs for Jenkins don't have anything related to user creation.
Actually, I have to create a new user followed by creating a new job for that user, all of this using an API.
You're right, there is no explicit CLI command for adding a user. But you could use groovy script for this (using the CLI for execution).
The details depend on how your Jenkins is configured.
For example, if your Jenkins uses its own user database, then you could add a new user by the following CLI call:
echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user1", "password123")' |
java -jar jenkins-cli.jar -s http://localhost/ groovy =
This shell command will create a new user with login "user1" and password "password123".
Here echo feeds a line of groovy code to a Jenkins CLI (note that = means that CLI should receive code from STDIN).
Also groovy script allows to manage user permissions, however, the exact code depends on what authorization strategy is used. You could use this sample script as a start.
This is how to create user after installation:
echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user", "password")' | java -jar jenkins-cli.jar -auth admin:c3a5dcd6bc3f45ee8d6c9f0f5abc14c0 -s http://localhost:8080/ groovy =
Where c3a5dcd6bc3f45ee8d6c9f0f5abc14c0 is automatically generated password present in log or in file (for ubuntu): /var/lib/jenkins/secrets/initialAdminPassword
echo and pipe didn't work on my Windows, so I ended up using a script file instead. It's also easier to add more logic in the script file. The script below will check existing user before adding a new user, and then set the user's email after account creation and give READ access using Matrix-based security. You can run it by saving the script into a file, say user-creation.groovy, and then run the following,
java -jar jenkins-cli.jar -s http://localhost/ groovy user-creation.groovy testUser testPassword testEmail#testEmail.com
import hudson.model.*
import hudson.security.*
import hudson.tasks.Mailer
def userId = args[0]
def password = args[1]
def email = args[2]
def instance = jenkins.model.Jenkins.instance
def existingUser = instance.securityRealm.allUsers.find {it.id == userId}
if (existingUser == null) {
def user = instance.securityRealm.createAccount(userId, password)
user.addProperty(new Mailer.UserProperty(email));
def strategy = (GlobalMatrixAuthorizationStrategy) instance.getAuthorizationStrategy()
strategy.add(Hudson.READ, userId)
instance.setAuthorizationStrategy(strategy)
instance.save()
}
I managed to get the following python snippet to create a user with ssh-key:
import json
import requests
def main():
data = {
'credentials': {
'scope': "GLOBAL",
'username': "jenkins",
'privateKeySource': {
'privateKey': "-----BEGIN RSA PRIVATE KEY-----\nX\n-----END RSA PRIVATE KEY-----",
'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"
},
'stapler-class': "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey"
}
}
payload = {
'json': json.dumps(data),
'Submit': "OK",
}
r = requests.post("http://%s:%d/credential-store/domain/_/createCredentials" % (HOSTNAME, 8080), data=payload)
if r.status_code != requests.codes.ok:
print r.text
It is sort of like a REST interface except that one has to know the internals of the code and the names of the classes that the objects are supposed to decode to.
I'm trying to configure jenkins from an ansible script (running externally to the jenkins server); since the java cli doesn't support creating the credentials the python snippet seems the way to go.
Building on #vitaleek's answer the following will grab the default admin credentials from the file and create a new user:
pass=`sudo cat /var/lib/jenkins/secrets/initialAdminPassword` && echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount("user1", "password123")' | sudo java -jar jenkins-cli.jar -auth admin:$pass -s http://localhost:8080/ groovy =
If you're like me and you couldn't find the jenkins-cli.jar at first, that can be pulled from your Jenkins server as follows:
curl -O http://127.0.0.1:8080/jnlpJars/jenkins-cli.jar