支持win/nix操作系统上修改host文件的脚本
调试了一下,可以使用
#!/usr/bin/perl -w
use strict;
if (@ARGV != 1) {
print "run program as ./*.pl [win|nix]\n";
exit(1);
}
my $dnsfile;
my $os_version = 0; # default for nix
if ($ARGV[0] eq "win") {
$dnsfile = "C:\\WINDOWS\\system32\\drivers\\etc\\hosts";
$os_version = 1; # 1 for win
} elsif ($ARGV[0] eq "nix") {
$dnsfile = "/etc/hosts";
}
print "input your command:\n";
print "(r for recover your orginal DNS setting)\n";
print "(m for modify DNS setting as the program set)\n";
print "(q for quit this program)\n";
my $cmd;
while (defined ($cmd = <STDIN>)) {
chomp($cmd);
if ($cmd eq "r") {
&restore;
} elsif ($cmd eq "m") {
my @newfile;
open FILE, "< hosts";
while (<FILE>) {
push(@newfile, $_);
}
if (-e $dnsfile.".user.bak") {
if (! open FILE, "< $dnsfile.user.bak") {
die "can't open $dnsfile.user.bak: $!";
exit(1);
}
} else {
if (! open FILE, "< $dnsfile") {
die "can't open $dnsfile: $!";
exit(1);
}
}
while (<FILE>) {
push(@newfile, $_);
}
if ($os_version == 0) {
system "/bin/sh", "-c", "rm $dnsfile";
} elsif ($os_version == 1) {
system "c:\\WINDOWS\\system32\\cmd.exe", "/c", "del $dnsfile";
}
if (! open FILE, "> $dnsfile") {
die "can not open $dnsfile: $!";
exit(1);
}
foreach my $newline (@newfile) {
print FILE "$newline";
}
close FILE;
} elsif ($cmd eq "q") {
print "the program will quit right now!\n";
&restore;
last;
}
}
sub restore {
if (-e "$dnsfile.user.bak") {
if ($os_version == 0) {
system "/bin/sh", "-c", "cp $dnsfile.user.bak $dnsfile";
} elsif ($os_version == 1) {
system "c:\\WINDOWS\\system32\\cmd.exe", "/c", "copy $dnsfile.user.bak $dnsfile";
}
} else {
if ($os_version == 0) {
system "/bin/sh", "-c", "cp $dnsfile $dnsfile.user.bak";
} elsif ($os_version == 1) {
system "c:\\WINDOWS\\system32\\cmd.exe", "/c", "copy $dnsfile $dnsfile.user.bak";
}
}
}
运行界面截图:
winXP(虚拟机)
Ubuntu