Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F61229825
createUser.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Sun, May 5, 08:50
Size
2 KB
Mime Type
text/x-python
Expires
Tue, May 7, 08:50 (2 d)
Engine
blob
Format
Raw Data
Handle
17452788
Attached To
R3127 blackdynamite
createUser.py
View Options
#!/usr/bin/python3
################################################################
# import getpass
import
os
import
stat
import
psycopg2
import
string
import
argparse
import
getpass
import
os
################################################################
from
random
import
randint
,
choice
from
psycopg2.extensions
import
ISOLATION_LEVEL_AUTOCOMMIT
################################################################
def
generatePassword
():
characters
=
string
.
ascii_letters
+
string
.
digits
password
=
""
.
join
(
choice
(
characters
)
for
x
in
range
(
randint
(
8
,
16
)))
return
password
################################################################
def
createUser
(
user
,
host
):
connection_params
=
dict
()
connection_params
[
"user"
]
=
user
if
host
is
not
None
:
connection_params
[
"host"
]
=
host
if
host
is
None
:
host
=
'localhost'
connection_params
[
"password"
]
=
getpass
.
getpass
(
'{0}@{1} password: '
.
format
(
connection_params
[
'user'
],
host
))
try
:
connection
=
psycopg2
.
connect
(
**
connection_params
)
except
Exception
as
e
:
raise
Exception
(
str
(
e
)
+
'
\n
'
+
'*'
*
30
+
'
\n
cannot connect to database
\n
'
+
'*'
*
30
)
new_user
=
input
(
'new login: '
)
connection
.
set_isolation_level
(
ISOLATION_LEVEL_AUTOCOMMIT
)
curs
=
connection
.
cursor
()
try
:
curs
.
execute
(
'create user {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
(
e
)
print
(
'Setting new password'
)
curs
.
execute
(
'grant create on database blackdynamite to {0}'
.
format
(
new_user
))
password
=
generatePassword
()
curs
.
execute
(
'alter role {0} with password
\'
{1}
\'
'
.
format
(
new_user
,
password
))
fname
=
'{0}.bd'
.
format
(
new_user
)
print
(
'Saving information to {0}'
.
format
(
fname
))
try
:
os
.
remove
(
fname
)
except
Exception
:
pass
bdconf
=
open
(
fname
,
'w'
)
bdconf
.
write
(
'password = {0}
\n
'
.
format
(
password
))
bdconf
.
write
(
'host = {0}'
.
format
(
host
))
bdconf
.
close
()
os
.
chmod
(
fname
,
stat
.
S_IREAD
)
################################################################
parser
=
argparse
.
ArgumentParser
(
description
=
'User creation tool for blackdynamite'
)
parser
.
add_argument
(
"--user"
,
type
=
str
,
help
=
"name of the user to create"
,
required
=
True
)
parser
.
add_argument
(
"--host"
,
type
=
str
,
help
=
"host to connect where to create the user"
,
default
=
None
)
args
=
parser
.
parse_args
()
args
=
vars
(
args
)
new_user
=
args
[
'user'
]
host
=
args
[
'host'
]
createUser
(
new_user
,
host
)
Event Timeline
Log In to Comment