Unix自動(dòng)化問題講解
我們在使用Unix的時(shí)候,經(jīng)常需要運(yùn)用到Unix自動(dòng)化的知識(shí)。今天,我們就來了解下Unix自動(dòng)化的知識(shí)。任務(wù)自動(dòng)化是一個(gè)很泛的主題。我將本節(jié)僅限于非交互式 簡單自動(dòng)化。對于交互式命令的Unix自動(dòng)化,Expect 是當(dāng)前可用的***工具。應(yīng)該要么了解它的語法,要么用 Perl Expect.pm 模塊??梢詮?CPAN 獲取 Expect.pm;請參閱參考資料以了解更多詳細(xì)信息。
利用 cfengine,可以根據(jù)任意標(biāo)準(zhǔn)Unix自動(dòng)化幾乎任何任務(wù)。但是,它的功能非常象 Makefile 功能,對變量的復(fù)雜操作是很難處理的。
當(dāng)發(fā)現(xiàn)需要運(yùn)行這樣的命令,該命令的參數(shù)來自于散列或通過單獨(dú)的函數(shù)時(shí),通常***切換到 shell 腳本或 Perl。由于 Perl 的功能,其可能是較好的選擇。雖然,不應(yīng)該將 shell 腳本棄為替代來使用。有時(shí),Perl 是不必要的,您只需要運(yùn)行一些簡單的命令。
Unix自動(dòng)化中,自動(dòng)添加用戶是一個(gè)常見問題??梢跃帉懽约旱?adduser.pl 腳本,或者用大多數(shù)現(xiàn)代 Unix 系統(tǒng)提供的 adduser 程序。請確保使用的所有 Unix 系統(tǒng)間語法是一致的,但不要嘗試編寫一個(gè)通用的 adduser 程序接口。
它太難了,在您認(rèn)為涵蓋了所有 Unix 變體后,遲早會(huì)有人要求 Win32 或 MacOS 版本。這不是僅僅用 Perl 就能解決的問題之一,除非您是非常有野心的。這里只是讓腳本詢問用戶名、密碼、主目錄等等,并以 system() 調(diào)用來調(diào)用 adduser。
清單 4:用簡單的腳本調(diào)用 adduser
- #!/usr/bin/perl -w
- use strict;
- my %values; # will hold the values to fill in
- # these are the known adduser switches
- my %switches = ( home_dir => '-d', comment => '-c', group => '-G',
- password => '-p', shell => '-s', uid => '-u');
- # this location may vary on your system
- my $command = '/usr/sbin/adduser ';
- # for every switch, ask the user for a value
- foreach my $setting (sort keys %switches, 'username')
- {
- print "Enter the $setting or press Enter to skip: ";
- $values{$setting} = ;
- chomp $values{$setting};
- # if the user did not enter data, kill this setting
- delete $values{$setting} unless length $values{$setting};
- }
- die "Username must be provided" unless exists $values{username};
- # for every filled-in value, add it with the right switch to the comma
- nd
- foreach my $setting (sort keys %switches)
- {
- next unless exists $values{$setting};
- $command .= "$switches{$setting} $values{$setting} ";
- }
- # append the username itself
- $command .= $values{username};
- # important - let the user know what's going to happen
- print "About to execute [$command]\n";
- # return the exit status of the command
- exit system($command);
Unix自動(dòng)化的一個(gè)問題,我們就講解到這里了。
【編輯推薦】