我怎么能用perl修改linux主机上的ssh_config文件?

时间:2011-04-06 17:34:37

标签: perl ssh

我有一个有趣的问题,我的脚本使用ssh访问我的vmware服务器,以便从中提取数据。我发现如果运行脚本的机器从未连接到服务器,脚本将无法运行,因为询问我连接的主机是否应该添加到我的已知主机文件中。

基于阅读一些论坛等人和类似问题的人,我提出了一个想法。我想修改“脚本主机”上的ssh_config文件,以排除对配置文件中指定的主机的已知主机检查。这可以通过我编写的配置脚本完成,该脚本会询问您生成xml配置文件的各种问题。

现在问题......

我需要修改配置文件,我认为最简单的方法是将文件粘贴到perl中并操纵它。我以前做过啜食但根据我所读到的,在特定主机上禁用某些ssh选项的指令必须在全局选项指令之前进行。

如何在当前文件中的2个文本块之间插入文本?

这就是我的ssh_config看起来像

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

**--This is what my modification need to go--**

Host *
#   ForwardAgent no
#   ForwardX11 no
#   ForwardX11Trusted yes
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   GSSAPIKeyExchange no
#   GSSAPITrustDNS no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   Port 22
#   Protocol 2,1
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160

1 个答案:

答案 0 :(得分:1)

您可以通过具有核心Tie::File模块的Perl阵列访问文件的行。例如,要使用offset:

插入一行
use Tie::File;
tie @array, 'Tie::File', $file or die "Can't tie $file";
splice @array, $offset, 0, $line;

您也可以遍历数组等。数组的更改会立即反映在文件中。