Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F79358726
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
Mon, Aug 26, 00:22
Size
1 KB
Mime Type
text/x-python
Expires
Wed, Aug 28, 00:22 (2 d)
Engine
blob
Format
Raw Data
Handle
20169449
Attached To
R3127 blackdynamite
createUser.py
View Options
#!/usr/bin/python
import
getpass
import
psycopg2
import
string
from
random
import
*
import
argparse
from
psycopg2.extensions
import
ISOLATION_LEVEL_AUTOCOMMIT
import
os
,
stat
################################################################
def
generatePassword
():
characters
=
string
.
ascii_letters
+
string
.
digits
password
=
""
.
join
(
choice
(
characters
)
for
x
in
range
(
randint
(
8
,
16
)))
return
password
################################################################
def
createUser
(
new_user
):
connection_params
=
dict
()
connection_params
[
"user"
]
=
'postgres'
try
:
connection
=
psycopg2
.
connect
(
**
connection_params
)
except
Exception
as
e
:
raise
Exception
(
str
(
e
)
+
'
\n
'
+
'*'
*
30
+
'
\n
cannot connect to database
\n
'
+
'*'
*
30
)
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
try
:
curs
.
execute
(
'create database {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
e
try
:
curs
.
execute
(
'alter database {0} owner to {0}'
.
format
(
new_user
))
except
Exception
as
e
:
print
e
curs
.
execute
(
'grant create on database {0} 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
)
bdconf
=
open
(
fname
,
'w'
)
bdconf
.
write
(
'password = {0}'
.
format
(
password
))
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
)
args
=
parser
.
parse_args
()
args
=
vars
(
args
)
new_user
=
args
[
'user'
]
createUser
(
new_user
)
Event Timeline
Log In to Comment