歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Unix知識 >> Unix資訊 >> Unix自動化問題講解

Unix自動化問題講解

日期:2017/3/6 11:38:34   编辑:Unix資訊

我們在使用Unix的時候,經常需要運用到Unix自動化的知識。今天,我們就來了解下Unix自動化的知識。任務自動化是一個很泛的主題。我將本節僅限於非交互式 簡單自動化。對於交互式命令的Unix自動化,Expect 是當前可用的最好工具。應該要麼了解它的語法,要麼用 Perl Expect.pm 模塊。可以從 CPAN 獲取 Expect.pm;請參閱參考資料以了解更多詳細信息。

利用 cfengine,可以根據任意標准Unix自動化幾乎任何任務。但是,它的功能非常象 Makefile 功能,對變量的復雜操作是很難處理的。

當發現需要運行這樣的命令,該命令的參數來自於散列或通過單獨的函數時,通常最好切換到 shell 腳本或 Perl。由於 Perl 的功能,其可能是較好的選擇。雖然,不應該將 shell 腳本棄為替代來使用。有時,Perl 是不必要的,您只需要運行一些簡單的命令。

Unix自動化中,自動添加用戶是一個常見問題。可以編寫自己的 adduser.pl 腳本,或者用大多數現代 Unix 系統提供的 adduser 程序。請確保使用的所有 Unix 系統間語法是一致的,但不要嘗試編寫一個通用的 adduser 程序接口。

它太難了,在您認為涵蓋了所有 Unix 變體後,遲早會有人要求 Win32 或 MacOS 版本。這不是僅僅用 Perl 就能解決的問題之一,除非您是非常有野心的。這裡只是讓腳本詢問用戶名、密碼、主目錄等等,並以 system() 調用來調用 adduser。

清單 4:用簡單的腳本調用 adduser

  1. #!/usr/bin/perl -w
  2. use strict;
  3. my %values; # will hold the values to fill in
  4. # these are the known adduser switches
  5. my %switches = ( home_dir => '-d', comment => '-c', group => '-G',
  6. password => '-p', shell => '-s', uid => '-u');
  7. # this location may vary on your system
  8. my $command = '/usr/sbin/adduser ';
  9. # for every switch, ask the user for a value
  10. foreach my $setting (sort keys %switches, 'username')
  11. {
  12. print "Enter the $setting or press Enter to skip: ";
  13. $values{$setting} = ;
  14. chomp $values{$setting};
  15. # if the user did not enter data, kill this setting
  16. delete $values{$setting} unless length $values{$setting};
  17. }
  18. die "Username must be provided" unless exists $values{username};
  19. # for every filled-in value, add it with the right switch to the comma
  20. nd
  21. foreach my $setting (sort keys %switches)
  22. {
  23. next unless exists $values{$setting};
  24. $command .= "$switches{$setting} $values{$setting} ";
  25. }
  26. # append the username itself
  27. $command .= $values{username};
  28. # important - let the user know what's going to happen
  29. print "About to execute [$command]\n";
  30. # return the exit status of the command
  31. exit system($command);

Unix自動化的一個問題,我們就講解到這裡了。

Copyright © Linux教程網 All Rights Reserved