def gen_ssh_key(username, password='', key_dir=os.path.join(KEY_DIR, 'user'), authorized_keys=True, home='/home', length=2048):
 logger.debug('\xe7\x94\x9f\xe6\x88\x90ssh key\xef\xbc\x8c \xe5\xb9\xb6\xe8\xae\xbe\xe7\xbd\xaeauthorized_keys')
 private_key_file = os.path.join(key_dir, (username + '.pem'))
 mkdir(key_dir, mode=777)
 if os.path.isfile(private_key_file):
  os.unlink(private_key_file)
 ret = bash(('echo -e  "y\n"|ssh-keygen -t rsa -f %s -b %s -P "%s"' % (private_key_file, length, password)))
 if authorized_keys:
  auth_key_dir = os.path.join(home, username, '.ssh')
  mkdir(auth_key_dir, username=username, mode=700)
  authorized_key_file = os.path.join(auth_key_dir, 'authorized_keys')
  with open((private_key_file + '.pub')) as pub_f:
   with open(authorized_key_file, 'w') as auth_f:
    auth_f.write(pub_f.read())
  os.chmod(authorized_key_file, 384)
  chown(authorized_key_file, username)

def gen_ssh_key ( username , password = '' , key_dir = os . path . join ( KEY_DIR , 'user' ) , authorized_keys = True , home = '/home' , length = 2048 ) : logger . debug ( '\xe7\x94\x9f\xe6\x88\x90ssh key\xef\xbc\x8c \xe5\xb9\xb6\xe8\xae\xbe\xe7\xbd\xaeauthorized_keys' ) private_key_file = os . path . join ( key_dir , ( username + '.pem' ) ) mkdir ( key_dir , mode = 777 ) if os . path . isfile ( private_key_file ) : os . unlink ( private_key_file ) ret = bash ( ( 'echo -e  "y\n"|ssh-keygen -t rsa -f %s -b %s -P "%s"' % ( private_key_file , length , password ) ) ) if authorized_keys : auth_key_dir = os . path . join ( home , username , '.ssh' ) mkdir ( auth_key_dir , username = username , mode = 700 ) authorized_key_file = os . path . join ( auth_key_dir , 'authorized_keys' ) with open ( ( private_key_file + '.pub' ) ) as pub_f : with open ( authorized_key_file , 'w' ) as auth_f : auth_f . write ( pub_f . read ( ) ) os . chmod ( authorized_key_file , 384 ) chown ( authorized_key_file , username )
generate a user ssh key in a property dir 生成一个用户ssh密钥对 .