2017-04-24 11 views
0

以下はpython関数です。すべての関数は、ほとんどのPython関数(200以上の関数)で同じ繰り返し行を使用します。Python関数の繰り返し行を削除する方法

私はそれをモジュールとして書いて、モジュールとしてインポートすることを計画しました。

以下は、すべての機能で繰り返される行です。

def abc(username, password, host, a, b, c, d, e): 

# VARIABLES THAT NEED CHANGED 

# Create instance of SSHClient object 
    remote_conn_pre = paramiko.SSHClient() 

# Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn_pre.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

# initiate SSH connection 
    remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False) 
    print "SSH connection established to %s" % host 
# Use invoke_shell to establish an 'interactive session' 
    remote_conn = remote_conn_pre.invoke_shell() 

# Send some commands and get the output 

第2の機能例:上記の関数で

def xyz(username, password, host, a, b): 

# VARIABLES THAT NEED CHANGED 

# Create instance of SSHClient object 
    remote_conn_pre = paramiko.SSHClient() 

# Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn_pre.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

# initiate SSH connection 
    remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False) 
    print "SSH connection established to %s" % host 
# Use invoke_shell to establish an 'interactive session' 
    remote_conn = remote_conn_pre.invoke_shell() 

# Send some commands and get the output 

は、別のスクリプトで呼び出しています。 注:以下の行は、機能のたびに繰り返されていません。

と、関数に異なる引数(引数の数が異なる)で記述されたすべての関数です。

すべての機能に重複行を削除し、それが何の問題もなく動作させるためにどのよう
def xyz(username, password, host, a, b): 
  1. 以下のような例。

上記の関数は、ssh接続の確立に使用されます。paramikoを使用します。

+0

"変更が必要なもの"とは具体的には何ですか? – jordanm

答えて

0

おそらく単なる関数にして、関数の引数とともにコマンドの名前を渡すこともできます。このようなもの:

def run_remote(username, password, host, command, *command_args): 
    # Create instance of SSHClient object 
    remote_conn = paramiko.SSHClient() 

    # Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

    # initiate SSH connection 
    remote_conn.connect(host, 
         username=username, 
         password=password, 
         look_for_keys=False, 
         allow_agent=False) 
    print "SSH connection established to %s" % host 
    # execute a remote command and return stdin, stdout, stderr 
    args_as_str = ' '.join([pipes.quote(arg) for arg in command_args]) 
    return remote_conn.exec_command("{} {}".format(command, args_as_str) 
+0

'args_as_str = [...]'は 'args_as_str = '' .join(...)'でなければなりません。また 'pipes.quote'は' command'です。 –

+0

@DanD。更新、良いキャッチ。 – jordanm

+0

* command_argsは複数の引数を意味しますか?それを説明してください – asteroid4u

関連する問題