您的位置:首页 > 数据库 > MySQL

批量生成Account/CableModem/CPE并写入Mysql

2011-06-16 14:20 696 查看
#version: 2011-06-16
#!/usr/local/bin/perl -w
use strict;
#use cwd;
use diagnostics;
use DBI;
use Data::UUID;
use LWP::UserAgent;
use LWP::Simple;
#use Win32;
#use Compress::Zlib;
#use Clipboard; or use Win32::Clipboard
#*****************************GLOBAL  VARIABLES****************************#
my $bDEBUG = 0;
my $bNoExecute = 0;
my ($TRUE, $FALSE, $SUCCESS, $FAILED) = (1,0,1,0);
my $osVersion = "";
my $NEWLINE = "/r/n";
#*****************************AUXILIARY  FUNCTIONS****************************#
sub DEBUG_INFO {
return if (!$bDEBUG);
if (defined(@_)) {
print "@_/n";
} else {
print "Not Defined!/n";
}
}
sub D {DEBUG_INFO(@_);}
sub P {print "@_/n";}
sub myd { my ($debug, @params) = @_; P(@params) if ($debug) ; }

sub LOG_FILE {
my($fileName, $bAppData, @logPara) = @_;  #bAppData -- append date to file or overwrite file
#DEBUG_INFO($fileName, $bAppData);
$fileName =~ s!//!/!ig;
my @pathAry = split('/', $fileName);
my $tmpPath = "";
for (my $i=0; $i<scalar(@pathAry)-1; $i++) {
$tmpPath .= $pathAry[$i] . '/';   #D($tmpPath);
mkdir($tmpPath, 0111) if (! -d $tmpPath);
}
if ($bAppData) {$fileName = " >> " . $fileName;  #append data
} else         {$fileName = " > "  . $fileName;}
open(tmpLogFile, $fileName) || die "Cannot open log file: $fileName!/n";
foreach (@logPara) {
my ($str0D, $str0A) = ('/r', '/n');
s/$str0D//ig;  #remove all '/r' chars
print tmpLogFile "$_/n";
}
close(tmpLogFile);
}
sub download_webpage {
my ($url, $savedFName) = @_;  D("In download_webpage() -- $savedFName/t$url");
my $userAgent = new LWP::UserAgent;
$userAgent->agent('Mozilla/5.0');
my $req = HTTP::Request->new('GET', $url);
#my $req = new HTTP::Request ('POST',$address);
$req->content_type('application/x-www-form-urlencoded');
#$req->content();
my $res = $userAgent->request($req);
LOG_FILE($savedFName, $FALSE, $res->as_string());
}#download_webpage
sub download_bin {
my ($url, $savedFName) = @_;  D("In download_bin() -- $savedFName/t$url");
my $outcome = get ($url);
open FILE,"> $savedFName" || die "$!";
binmode(FILE);
print FILE $outcome;
close FILE;
}
sub send_request {
my ($url, $reqStr) = @_;  D("In send_request() -- $url/n$reqStr");
my $ua = LWP::UserAgent -> new();
#$ua->agent('Mozilla/5.0');
$ua->agent('Jakarta Commons-HttpClient/3.1');
#request
my $req = new HTTP::Request ('POST',$url);
#$req->content_type('application/x-www-form-urlencoded');
$req->content_type('text/xml;charset=UTF-8');
$req->content($reqStr);
#response
my $resp = $ua->request($req);  #D($res->as_string());
#D($resp->is_success());
#D($resp->message());
my $respStr = $resp->content();
if ($respStr=~/Error/i) {
P("** Send reqeust got ERROR! **/nExiting.../n"); exit 0;
}
}#send_request
sub trim($) {
my $string = shift;
$string =~ s/^/s+//;  $string =~ s//s+$//;
return $string;
}
sub isEmptyStr {
my ($result, $str) = (0, @_);
$result = 1 if (!defined($str) || $str eq "" || $str=~m/^/s+$/ig);
return $result;
}
sub parse_args {
P(@_);
for (my $i=0; $i<scalar(@_); $i++) {
if ($_[$i] eq "-debug") {
$bDEBUG = $TRUE;   #D("bDEBUG is set to: $bDEBUG");
} elsif ($_[$i] eq "-noexec") {
$bNoExecute = $TRUE;
} else {
}
}
if (defined $^O) {$osVersion =  $^O;} else {$osVersion = "win32"; }  D("osVersion is: $osVersion");
}
my $notifCnt = 0;
sub showAsyncMsgBox {
my ($msgStr) = @_;
my $choice = 4;  #init value to 'retry'
$notifCnt ++;
my $pid = fork();
if (not defined $pid) {
print "resources not avilable./n";
} elsif ($pid == 0) {
D("THE CHILD Thread/n");
$choice = Win32::MsgBox($msgStr, 48+5, "Notification_$notifCnt") if ($osVersion =~ /win32/i);
D("The choice is $choice");
if ($choice == 4) {  #4 -- retry
#Do nothing, continue to watch on this stock
} else {
}
exit 1;
} else {  D("THE PARENT Thread/n");  }
}
###############################################################################
sub main {
print_usage();
my $option = <STDIN>;
$option = '' if (!defined $option);
#genOneAccount();
#genManyAccounts();
genManyAccountsToDB();
}
sub genOneAccount {
my $MAX_ACCOUNT_NUM = 51;
my $info = "<?xml version=/"1.0/" encoding=/"UTF8/" ?>/n<XmlInterfaceRequest>/n  <AddAccount>/n";
for (my $i=1; $i<=$MAX_ACCOUNT_NUM; $i++) {
$info = sprintf("%s    <Account>/n", $info);
$info = sprintf("%s      <AccountId>Account_perf_%d</AccountId>/n", $info, $i);
$info = sprintf("%s      <NetworkElementName>cmts_107</NetworkElementName>/n", $info);
$info = sprintf("%s      <EndUser> <EndUserId>she/@company.com</EndUserId> </EndUser>/n", $info);
$info = sprintf("%s      <CableModem>/n", $info);
$info = sprintf("%s        <CmMacAddr>11:11:11:11:11:%d</CmMacAddr>/n", $info, $i);
$info = sprintf("%s        <CmIpAddr>10.15.25.%d</CmIpAddr>/n", $info, $i);
for (my $j=1; $j<=5; $j++) {
$info = sprintf("%s          <Cpe> <CpeIpAddr>10.15.24.%d</CpeIpAddr> </Cpe>/n", $info, ($i-1)*5+$j);
}
$info = sprintf("%s      </CableModem>/n", $info);
$info = sprintf("%s    </Account>/n/n", $info);
}
$info = sprintf("%s  </AddAccount>/n</XmlInterfaceRequest>/n/n", $info);
P($info);
LOG_FILE("./AddAccount_multi_account.xml", $FALSE, $info);
}
sub genManyAccounts {
my $MAX_CPE_NUM = 524286;
my $CPE_NUM_PER_CABLEMODEM = 5;
my $CMTS_NAME = "cmts_self";
my $cmMacAddr = "11:00:00:00:00:00";
my $cmIpAddr  = "11.0.0.0";
my $cpeIpAddr = "10.0.0.0";
my $totalInfo = "<?xml version=/"1.0/" encoding=/"UTF8/" ?>/n<XmlInterfaceRequest>/n  <AddAccount>/n";
my @cpeInfoAry = ();
for (my $i=1; $i<=$MAX_CPE_NUM; $i++) {
P(sprintf("Generating account for CPE No.%d to %d...",$i-254,$i) )  if ($i%255 == 0);
my $info = "";
$cmMacAddr = getNextMacAddr($cmMacAddr, ":", 16);
$cmIpAddr  = getNextMacAddr($cmIpAddr, "//.", 10);
$cpeIpAddr = getNextMacAddr($cpeIpAddr, "//.", 10);
$info = sprintf("%s    <Account>/n", $info);
$info = sprintf("%s      <AccountId>Account_perf_%d</AccountId>/n", $info, $i);
$info = sprintf("%s      <NetworkElementName>$CMTS_NAME</NetworkElementName>/n", $info);
$info = sprintf("%s      <EndUser> <EndUserId>she/@company.com</EndUserId> </EndUser>/n", $info);
$info = sprintf("%s      <CableModem>/n", $info);
$info = sprintf("%s        <CmMacAddr>%s</CmMacAddr>/n", $info, $cmMacAddr);
$info = sprintf("%s        <CmIpAddr>%s</CmIpAddr>/n", $info, $cmIpAddr);
#for (my $j=1; $j<=1; $j++) {
$info = sprintf("%s          <Cpe> <CpeIpAddr>%s</CpeIpAddr> </Cpe>/n", $info, $cpeIpAddr);
#}
$info = sprintf("%s      </CableModem>/n", $info);
$info = sprintf("%s    </Account>/n/n", $info);
push(@cpeInfoAry, $info);
}
foreach(@cpeInfoAry) { $totalInfo .= $_ }
$totalInfo = sprintf("%s  </AddAccount>/n</XmlInterfaceRequest>/n/n", $totalInfo);
#P($info);
LOG_FILE("./AddAccount_multi_account.xml", $FALSE, $totalInfo);
}
sub genManyAccountsToDB {
my $debug = $TRUE;
my $MAX_CPE_NUM = 65534;
my $CMTS_NAME = "cmts_self";
my $cmMacAddr = "11:00:00:00:00:00";
my $cmIpAddr  = "11.0.0.0";
my $cpeIpAddr = "12.0.0.0";
my ($accUid, $cmUid, $cpeUid) = ("", "", "");
my $accCnt = 0;

my $dbh = DBI->connect( "dbi:mysql:camiant:localhost:3306", "root", "root");

my @accountRecColAry = ();
my %accountRecTbl = (
"uid" => "",  "accountid" => "",  "networkelementname" => "cmts_self",
#"subscribergroupname" => "",  "subscriberdata" => "",
"changeflag" => "0", "source" => "ossi_xml",
"createtimestamp" => "",          "createuser" => "1",
"modifytimestamp" => "",        	"modifyuser" => "NULL",
);
my @cmRecColAry = ();
my %cmRecTbl = (
"uid" => "", "cmmacaddr" => "", "cmipaddr" => "", "upbladeindex" => "0",
"upchannelindex" => "0", "downbladeindex" => "0",   "downchannelindex" => "0",
"docsisversion" => "0",  "maxflows" => "0",         "maxclassifiers" => "0",
"acctid" => "",          "changeflag" => "0",       "createtimestamp" => "",
"createuser" => "1",     "modifytimestamp" => "",  "modifyuser" => "NULL",
);
my @cpeRecColAry = ();
my %cpeRecTbl = (
"uid" => "", "cpemacaddr" => "", "cpeipaddr" => "", "cablemodemid" => "",
"changeflag" => "0",      "source" => "ossi",
"createtimestamp" => "",  "createuser" => "1",
"modifytimestamp" => "",  "modifyuser" => "NULL",
);

my $sqlStat = "";
for (my $counter=1; $counter<=$MAX_CPE_NUM; $counter++) {
#myd($debug, $counter);

#generate records in Account Table
$accountRecTbl{"uid"} = getUUID(15);
$accountRecTbl{"accountid"} = "Account_perf_".++$accCnt;
$accountRecTbl{"createtimestamp"} = getFormatTime();
$accountRecTbl{"modifytimestamp"} = getFormatTime();

my @accountRecColAry = keys %accountRecTbl;
$sqlStat= "INSERT INTO account (";
for (my $i=0; $i<scalar(@accountRecColAry); $i++) {
my $key = $accountRecColAry[$i];
$sqlStat .= "$key";
$sqlStat .= "," if ($i<scalar(@accountRecColAry)-1 );
}
$sqlStat .= " ) VALUES (";
for(my $i=0; $i<scalar(@accountRecColAry); $i++) {
my $key = $accountRecColAry[$i];
$sqlStat .= "'$accountRecTbl{$key}'";
$sqlStat .= "," if ($i<scalar(@accountRecColAry)-1 );
}
$sqlStat .= " )";
runSqlStat($dbh, $sqlStat);  myd($debug, $sqlStat);

#generate records in CableModem Table
$cmRecTbl{"uid"} = getUUID(15);
$cmMacAddr = getNextMacAddr($cmMacAddr, ":", 16);
$cmRecTbl{"cmmacaddr"} = $cmMacAddr;
$cmIpAddr = getNextMacAddr($cmIpAddr, "//.", 10);
$cmRecTbl{"cmipaddr"} = $cmIpAddr;
$cmRecTbl{"acctid"} = $accountRecTbl{"uid"};
$cmRecTbl{"createtimestamp"} = getFormatTime();
$cmRecTbl{"modifytimestamp"} = getFormatTime();
my @cmRecColAry = keys %cmRecTbl;
$sqlStat= "INSERT INTO cablemodem (";
for (my $i=0; $i<scalar(@cmRecColAry); $i++) {
my $key = $cmRecColAry[$i];
$sqlStat .= "$key";
$sqlStat .= "," if ($i<scalar(@cmRecColAry)-1 );
}
$sqlStat .= " ) VALUES (";
for(my $i=0; $i<scalar(@cmRecColAry); $i++) {
my $key = $cmRecColAry[$i];
$sqlStat .= "'$cmRecTbl{$key}'";
$sqlStat .= "," if ($i<scalar(@cmRecColAry)-1 );
}
$sqlStat .= " )";
runSqlStat($dbh, $sqlStat);  myd($debug, $sqlStat);

#generate records in CPE Table
my $cnt = int(rand(2))+1;
for (my $j=0; $j<$cnt; $j++) {
$cpeRecTbl{"uid"} = getUUID(15);
$cpeRecTbl{"cpemacaddr"} = "00:00:00:00:00:00";
$cpeIpAddr = getNextMacAddr($cpeIpAddr, "//.", 10);
$cpeRecTbl{"cpeipaddr"} = $cpeIpAddr;
$cpeRecTbl{"cablemodemid"} = $cmRecTbl{"uid"};
$cpeRecTbl{"createtimestamp"} = getFormatTime();
$cpeRecTbl{"modifytimestamp"} = getFormatTime();

my @cpeRecColAry = keys %cpeRecTbl;
$sqlStat= "INSERT INTO cpe (";
for (my $i=0; $i<scalar(@cpeRecColAry); $i++) {
my $key = $cpeRecColAry[$i];
$sqlStat .= "$key";
$sqlStat .= "," if ($i<scalar(@cpeRecColAry)-1 );
}
$sqlStat .= " ) VALUES (";
for(my $i=0; $i<scalar(@cpeRecColAry); $i++) {
my $key = $cpeRecColAry[$i];
$sqlStat .= "'$cpeRecTbl{$key}'";
$sqlStat .= "," if ($i<scalar(@cpeRecColAry)-1 );
}
$sqlStat .= " )";

runSqlStat($dbh, $sqlStat);  myd($debug, $sqlStat);

if ($j >= 1) {
$counter++;
}
}

myd($debug, "/n");

}
}
sub Test01 {
### Probe DBI for the installed drivers
my @drivers = DBI->available_drivers();
die "No drivers found!/n" unless @drivers; # should never happen
### Iterate through the drivers and list the data sources for each one
foreach my $driver ( @drivers ) {
print "Driver: $driver/n";
#    my @dataSources = DBI->data_sources( $driver );
#    foreach my $dataSource ( @dataSources ) {
#      print "/tData Source is $dataSource/n";
#    }
print "/n";
}
my $dbh = DBI->connect( "dbi:mysql:camiant:localhost:3306", "root", "root");
#$dbh->do("SELECT * from account ");
my $sth = $dbh->prepare( "SELECT * FROM account" );
$sth->execute or die "Can't execute SQL statement: $DBI::errstr/n";
### Retrieve the returned rows of data
my @row;
while ( @row = $sth->fetchrow_array( ) ) {
print "Row: @row/n";
}
my $uuid = getUUID(15);
my %accountRecTbl = (
"uid" => $uuid,
"accountid" => "Account12",
"networkelementname" => "cmts_self",
"subscribergroupname" => "NULL",
"changeflag" => "0",
"source" => "ossi_xml",
"createtimestamp" => "",
"createuser" => "1",
"modifytimestamp" => "",
"modifyuser" => "NULL2",
);
$accountRecTbl{"createtimestamp"} = getFormatTime();
$accountRecTbl{"modifytimestamp"} = getFormatTime();
my @accountRecColAry = keys %accountRecTbl;
my $sqlStat = "INSERT INTO account (";
for (my $i=0; $i<scalar(@accountRecColAry); $i++) {
my $key = $accountRecColAry[$i];
$sqlStat .= "$key";
$sqlStat .= "," if ($i<scalar(@accountRecColAry)-1 );
}
$sqlStat .= " ) VALUES (";
for(my $i=0; $i<scalar(@accountRecColAry); $i++) {
my $key = $accountRecColAry[$i];
$sqlStat .= "'$accountRecTbl{$key}'";
$sqlStat .= "," if ($i<scalar(@accountRecColAry)-1 );
}
$sqlStat .= " )";
P($sqlStat);
$sth = $dbh->prepare($sqlStat);
$sth->execute();
}
sub Test02 {
for (1..100) {
print "Your lucky number for today is: " . int(rand(2)+1) . "/n";
}
my $ug    = new Data::UUID;
my $uuid1 = $ug->to_string($ug->create());
$uuid1 = $ug->create_hex();
$uuid1 = $ug->create_from_name_str(NameSpace_URL, "www.mycompany.com");
printf "$uuid1/n";
}
sub getFormatTime {
my $result = "";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$result = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $year+1900,$mon+1,$mday,$hour,$min,$sec);
return $result;
}
sub getUUID {
my ($uuidLen) = @_;
my $ug   = new Data::UUID;
my $uuid = $ug->create_hex();  D("uuid is: $uuid");
my $result = "";
for (my $i=2; $i<length($uuid); $i+=2) {
$result = sprintf("%s%d", $result, hex(substr($uuid,$i,2)) );
}
if (length($result) > $uuidLen) {
$result = substr($result,0,$uuidLen);
}
return $result;
}
sub runSqlStat {
my ($dbh, $sqlStat) = @_;
my $sth = $dbh->prepare($sqlStat);
if ($bNoExecute) {

} else {
$sth->execute();
}
}
sub getNextMacAddr {
my ($oriAddr, $delimeter, $radix) = @_;  D($oriAddr, $delimeter);
my @addrAry = split(/$delimeter/, $oriAddr);
#D(@addrAry);
my $result = "";
for (my $i=scalar(@addrAry)-1; $i>0; $i--) {
#D("addrAry[$i] is: ", $addrAry[$i]);
my $tmpVal = $addrAry[$i];
if ($radix == 16) {
$tmpVal = hex($addrAry[$i]);
}
if ($tmpVal < 0xff) {
if ($radix == 16) {
$addrAry[$i] = sprintf("%02x", $tmpVal+1);
} else {
$addrAry[$i] = sprintf("%d", $tmpVal+1 );
}
last;
} else {
$addrAry[$i] = "00";
}
}
for (my $i=0; $i<scalar(@addrAry); $i++) {
$result .= uc($addrAry[$i]);
$delimeter =~ s/////ig;
$result .= $delimeter if ($i<scalar(@addrAry)-1);
}
return $result;
}

sub print_usage {
print"/n";
printf("*** Function SELECTOR ***/n");
printf("* 1. TEST01             */n");
printf("* 2. TEST02             */n");
printf("*************************/n");
printf("/nChoose An Option: ");
}
###############################################################################
parse_args(@ARGV);
if (1) {
main();
} else {
Test02();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: